Cannot find symbol using BigDecimal - java

I'm doing my first attempts to use BigDecimal. It seems tricky.i am running into an issue and i would like to understand what is causing it.
public static String nominator(String nbrPeople)
{
BigDecimal nom = new BigDecimal("365") ;
BigDecimal days = new BigDecimal("365") ;
int limit = Integer.parseInt(nbrPeople);
for (int i = 0 ; i < limit ; i++ )
{
days = days.substract(i) ;
nom = nom.multiply(days) ;
}
return nbrPeople ;
}
this is part of a larger program. it is a method that should compute something like this:
365 x (365-1) x (365-2) x (365-3) etc depending on the value of nbrPeople passed in.
i would like to understand why i get the following error message:
cannot find symbol
method substract(int)
not looking for a discussion on factorials but rather on the use of BigDecimal (or BigInteger). I'm using BigDecimal because at a later stage i will need to divide, resulting in floating point.
EDIT
EDIT 2
first edit removed (code) to make the post more readable- the correct code has been posted below by a kind programmer

Because the method is named subtract not substract.
And the parameter has to be BigInteger too:
http://download.oracle.com/javase/6/docs/api/java/math/BigInteger.html#subtract(java.math.BigInteger)

You are attempting to subtract an int from a BigDecimal. Since there is no method subtract(int x) on the BigDecimal class, you get the cannot find symbol compiler error.

This should work:
public static String nominator(String nbrPeople)
{
BigDecimal nom = new BigDecimal("365") ;
BigDecimal days = new BigDecimal("365") ;
int limit = Integer.parseInt(nbrPeople);
for (int i = 0 ; i < limit ; i++ )
{
days = days.subtract(new BigDecimal(i)) ;
nom = nom.multiply(days) ;
}
return nbrPeople ;
}
as there is no BigDecimal.subtract(int) method, only a BigDecimal.subtract(BigDecimal) method.

Typo - you misspelled "subtract".

Should be subtract ( with a single s )
Whenever you see cannot find symbol message, you are trying to use a method that doesn't exist or a variable that doesn't exists. Most of the time ( as in this case ) due to a misspelling or because you didn't import the class.

BigDecimal can only subtract another BigDecimal. you are subtracting an int. See
http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#subtract(java.math.BigDecimal)

http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#subtract(java.math.BigDecimal
import java.math.BigDecimal;
import java.util.Scanner;
public class BigDecimal_SumExample {
public static void main(String args[]) {
BigDecimal number1;
BigDecimal number2;
BigDecimal sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of number 1");
number1 = sc.nextBigDecimal();
System.out.println("Enter the value of number 2");
number2 = sc.nextBigDecimal();
BigDecimal a = new BigDecimal(""+number1);
BigDecimal b = new BigDecimal(""+number2);
BigDecimal result = a.add(b);
System.out.println("Sum is Two numbers : -> ");
System.out.println(result);
}
}
**Output is**
Enter the value of number 1
68237161328632187132612387312687321678312612387.31276781237812
Enter the value of number 2
31232178631276123786321712369812369823162319862.32789129819299
Sum is Two Big Decimal numbers : ->
99469339959908310918934099682499691501474932249.64065911057111

Related

Java code snippet to trim the decimal places in a number based on a condition [duplicate]

I am invoking a method called "calculateStampDuty", which will return the
amount of stamp duty to be paid on a property. The percentage calculation works
fine, and returns the correct value of "15000.0". However, I want to display the value to
the front end user as just "15000", so just want to remove the decimal and any preceding values
thereafter. How can this be done? My code is below:
float HouseValue = 150000;
double percentageValue;
percentageValue = calculateStampDuty(10, HouseValue);
private double calculateStampDuty(int PercentageIn, double HouseValueIn){
double test = PercentageIn * HouseValueIn / 100;
return test;
}
I have tried the following:
Creating a new string which will convert the double value to a string, as per below:
String newValue = percentageValue.toString();
I have tried using the 'valueOf' method on the String object, as per below:
String total2 = String.valueOf(percentageValue);
However, I just cannot get a value with no decimal places. Does anyone know
in this example how you would get "15000" instead of "15000.0"?
Thanks
Nice and simple. Add this snippet in whatever you're outputting to:
String.format("%.0f", percentageValue)
You can convert the double value into a int value.
int x = (int) y where y is your double variable. Then, printing x does not give decimal places (15000 instead of 15000.0).
I did this to remove the decimal places from the double value
new DecimalFormat("#").format(100.0);
The output of the above is
100
You could use
String newValue = Integer.toString((int)percentageValue);
Or
String newValue = Double.toString(Math.floor(percentageValue));
You can convert double,float variables to integer in a single line of code using explicit type casting.
float x = 3.05
int y = (int) x;
System.out.println(y);
The output will be 3
I would try this:
String numWihoutDecimal = String.valueOf(percentageValue).split("\\.")[0];
I've tested this and it works so then it's just convert from this string to whatever type of number or whatever variable you want. You could do something like this.
int num = Integer.parseInt(String.valueOf(percentageValue).split("\\.")[0]);
Try this you will get a string from the format method.
DecimalFormat df = new DecimalFormat("##0");
df.format((Math.round(doubleValue * 100.0) / 100.0));
Double d = 1000d;
System.out.println("Normal value :"+d);
System.out.println("Without decimal points :"+d.longValue());
Use
Math.Round(double);
I have used it myself. It actually rounds off the decimal places.
d = 19.82;
ans = Math.round(d);
System.out.println(ans);
// Output : 20
d = 19.33;
ans = Math.round(d);
System.out.println(ans);
// Output : 19
Hope it Helps :-)
the simple way to remove
new java.text.DecimalFormat("#").format(value)
The solution is by using DecimalFormat class. This class provides a lot of functionality to format a number.
To get a double value as string with no decimals use the code below.
DecimalFormat decimalFormat = new DecimalFormat(".");
decimalFormat.setGroupingUsed(false);
decimalFormat.setDecimalSeparatorAlwaysShown(false);
String year = decimalFormat.format(32024.2345D);
With a cast. You're basically telling the compiler "I know that I'll lose information with this, but it's okay". And then you convert the casted integer into a string to display it.
String newValue = ((int) percentageValue).toString();
You can use DecimalFormat, but please also note that it is not a good idea to use double in these situations, rather use BigDecimal
String truncatedValue = String.format("%f", percentageValue).split("\\.")[0]; solves the purpose
The problem is two fold-
To retain the integral (mathematical integer) part of the double. Hence can't typecast (int) percentageValue
Truncate (and not round) the decimal part. Hence can't use String.format("%.0f", percentageValue) or new java.text.DecimalFormat("#").format(percentageValue) as both of these round the decimal part.
Type casting to integer may create problem but even long type can not hold every bit of double after narrowing down to decimal places. If you know your values will never exceed Long.MAX_VALUE value, this might be a clean solution.
So use the following with the above known risk.
double mValue = 1234567890.123456;
long mStrippedValue = new Double(mValue).longValue();
Alternatively, you can use the method int integerValue = (int)Math.round(double a);
Double i = Double.parseDouble("String with double value");
Log.i(tag, "display double " + i);
try {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0); // set as you need
String myStringmax = nf.format(i);
String result = myStringmax.replaceAll("[-+.^:,]", "");
Double i = Double.parseDouble(result);
int max = Integer.parseInt(result);
} catch (Exception e) {
System.out.println("ex=" + e);
}
declare a double value and convert to long convert to string and formated to float the double value finally replace all the value like 123456789,0000 to 123456789
Double value = double value ;
Long longValue = value.longValue();
String strCellValue1 = new String(longValue.toString().format("%f",value).replaceAll("\\,?0*$", ""));
public class RemoveDecimalPoint{
public static void main(String []args){
System.out.println(""+ removePoint(250022005.60));
}
public static String removePoint(double number) {
long x = (long) number;
return x+"";
}
}
This should do the trick.
System.out.println(percentageValue.split("\\.")[0]);
Try:
String newValue = String.format("%d", (int)d);

cast String with period and comma to int

how to cast String with period and comma to int, like
String a "9.000,00"
int b = Integer.parseInt(a);
when I run this code, I get an error message : Exception in thread "main" java.lang.NumberFormatException: For input string: "9.000,00"
If you want to get as result 900000 then simply remove all , and . and parse it with for instance with Integer.parseInt or Long.parseLong or maybe even better use BigInteger if number can be large.
String a = "9.000,00";
BigInteger bn = new BigInteger(a.replaceAll("[.,]", ""));
System.out.println(bn);
Output: 900000
But if you want to parse 9.000,00 into 9000 (where ,00 part is decimal fraction) then you can use NumberFormat with Locale.GERMANY which uses form similar to your input: 123.456,78
String a = "9.000,00";
NumberFormat format = NumberFormat.getInstance(Locale.GERMANY);
Number number = format.parse(a);
double value = number.doubleValue();
//or if you want int
int intValue = number.intValue();
System.out.println(value);
System.out.println(intValue);
Output:
9000.0
9000
final String a = "9.000,00";
final NumberFormat format = NumberFormat.getInstance(Locale.GERMAN); // Use German locale for number formats
final Number number = format.parse(a); // Parse the number
int i = number.intValue(); // Get the integer value
Reference
To do that, you need to use java.text.NumberFormat and NumberFormat.getInstance(Locale.FRANCE) (or another compatible Locale)
import java.text.NumberFormat;
import java.util.Locale;
class Test {
public static void main(String[] args) throws Exception {
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
String a = "9.000,00";
a = a.replaceAll("\\.", "");
Number number = format.parse(a);
double d = number.doubleValue();
int c = (int) Math.floor(d);
System.out.println(c);
}
}
prints 9000 as you want ( and now is an int ) !
If I print every intermediate step :
import java.text.NumberFormat;
import java.util.*;
class test {
public static void main(String[] args) throws Exception {
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
String a = "9.000,00";
a = a.replaceAll("\\.", "");
System.out.println(a); // prints 9000,00
Number number = format.parse(a);
System.out.println(number); // prints 9000
double d = number.doubleValue();
System.out.println(d); // prints 9000.0
int c = (int) Math.floor(d);
System.out.println(c); // prints 9000
}
}
so if Okem you want 9000,00 as you're saying in your comment, you just need
a = a.replaceAll("\\.", "");
System.out.println(a);
which gives you an output of 9000,00
I hope that helps.
Try this -
String a = "9.000,00";
a = a.replace(",","");
a = a.replace(".","");
int b = Integer.parseInt(a);
I think DecimalFormat.parse is the Java 7 API way to go:
String a = "9.000,00";
DecimalFormat foo = new DecimalFormat();
Number bar = foo.parse(a, new ParsePosition(0));
After that, you go and be happy with the Number you just got.
If you want the answer to be 900000 (it doesn't make sense to me, but I'm replying to your question) and put that into an int go with:
int b = Integer.parseInt(a.replaceAll(",","").replaceAll("\\.",""));
as already outlined in the comments.

How can i add two double values without exponential in android

Please help me to solve this. I trying to get value from textview and stored as string. Then it converts to double. While converting up to 7 characters functioning normally but if i try to add more than 7 result is 1.23456789E8. Here is my code
String value = tvInput.getText().toString();
\\tvInput is my textView
Double result = 0.0;
Double input1=0.0;
Double input2=0.0;
input=Double.parseDouble(value);
result = input1 + input2;
tvInput.setText(Double.toString(result));
if i give input1 value as 1234567 and input2 as 1234567 i am getting correct result but if give input1 as 12345678 and input2 as 3. the output is 1.2345681E7
The value you get is correct, the issue is with the way you print it.
You're relying on toString for a double output; if you want to guarantee not to have an exponential notation, you should format it using a DecimalFormat, or with String.format;
DecimalFormat myFormatter = new DecimalFormat("############");
tvInput.setText(myFormatter.format(result));
Also see the format documentation
The behavior you describe is consistent with the javadoc. You could use String.format instead.
Either 12345678 and 1.2345678E7 are exactly the same number. No trouble with that
Your trouble is with the representation, if E>6 then toString() use scientific notation. You may want to use NumberFormat for this.
Use String.format: example
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
String i1 = "12345678";
String i2 = "3";
double d1 = Double.parseDouble(i1);
double d2 = Double.parseDouble(i2);
double d = d1 + d2;
System.out.println( String.format("%f", d) );
}
}
Why don't use Integer instead?
String value = tvInput.getText().toString();
\\tvInput is my textView
int result = 0;
int input1 = 0;
int input2 = 0;
input=Integer.parseInt(value);
result = input1 + input2;
tvInput.setText(Integer.toString(result));

Any way to avoid results containing "9.223372036854776E18"

I'm making a program that turns a large number into a string, and then adds the characters of that string up. It works fine, my only problem is that instead of having it as a normal number, Java converts my number into standard form, which makes it hard to parse the string. Are there any solutions to this?
public static void main(String ags[]) {
long nq = (long) Math.pow(2l, 1000l);
long result = 0;
String tempQuestion = Double.toString(nq);
System.out.println(tempQuestion);
String question = tempQuestion.substring(0, tempQuestion.length() - 2);
for (int count = 0; count < question.length(); count++) {
String stringResult = question.substring(count, count + 1);
result += Double.parseDouble(stringResult);
}
System.out.println(result);
Other answers are correct, you could use a java.text.NumberFormat (JavaDoc) to format your output. Using printfis also an option for formatting, similar to NumberFormat. But I see something else here. It looks like you mixed up your data types: In
nq = (long) Math.pow(2l, 1000l);
you are already truncating the double return value from Math to a long. Then you should use long as data type instead of double for the conversion. So use Long.toString(long), this will not add any exponent output.
Use Long.toString(nq) instead of Double.toString(nq); in your code.
As you say: "NumberFormat". The class.
BigInteger is easy to use and you don't risk precision problems with it. (In this particular instance I don't think there is a precision problem, because Math.pow(2, 1001) % 100000 returns the correct last 5 digits, but for bigger numbers eventually you will lose information.) Here's how you can use BigInteger:
groovy:000> b = new BigInteger(2L)
===> 2
groovy:000> b = b.pow(1001)
===> 214301721437253464189685009812000362112280962341106721488750077674070210224
98722449863967576313917162551893458351062936503742905713846280871969155149397149
60786913554964846197084214921012474228375590836430609294996716388253479753511833
1087892154125829142392955373084335320859663305248773674411336138752
groovy:000> ((b + "").toList().collect {new Integer(it)}).inject(0) {sum, n -> sum + n}
===> 1319
Here's the same thing in Java:
public class Example
{
public static void main(String[] args)
{
int sum = 0;
for (char ch : new java.math.BigInteger("2").pow(1001).toString().toCharArray()) {
sum += Character.digit(ch, 10);
}
System.out.println(sum);
}
}
Link to the javadoc for NumberFormat: Javadoc
just replace last line:
System.out.println(result);
with
System.out.printf("%d", result);

Double datatype formatting

This is a very trivial problem for you guys. Please suggest me the way to achieve the optimal solution. My requirement is, I have an incoming Double value, so if the value after the decimal point is 0, than truncate everything after the decimal. For example: 30.0 should become 30, where as 30.12 or 30.1 should stay as it is. Till now I have only figured out a way to know how many digits are there after the decimal point.
package com.convertdatatypes;
public class DoubleCheck {
public static void main(String args[]){
Double value = 30.153;
String val = value.toString();
String[] result = new String[2];
for(int i=0; i<val.length(); i++){
result = val.split("\\.");
System.out.println("Number of Decimals in: " + val + " : " + result[1].length());
}
}
}
use java's DecimalFormat with the following pattern:
0.##
See http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html
Another approach is to use the following
double value = 30.153;
Object value2 = value == (long) value ? String.valueOf((long) value) : value;
System.out.println("Number of Decimals in: " + value2);
This way it prints as a long if the value is unchanged or a double otherwise.

Categories