I've been trying to sum up decimal values using double in java and it doesn't work well, got a wrong answer.
I've already tried with Double, Float, BigDecimal.
{
double a = 2595.00;
double b = -1760.76;
double c = -834.00;
double d = -.24;
System.out.print(a+b+c+d);
}
The expected result should be "0" But Got 9.1038288019262836314737796783447265625E-15
You can use BigDecimal for this purpose and make sure you input the numbers as String in the BigDecimal constructor:
BigDecimal a = new BigDecimal("2595.00");
BigDecimal b = new BigDecimal("-1760.76");
BigDecimal c = new BigDecimal("-834.00");
BigDecimal d = new BigDecimal("-.24");
System.out.println(a.add(b).add(c).add(d));
Live Example
Output is:
0.00
From the Java docs for BigDecimal(String):
This is generally the preferred way to convert a float or double into
a BigDecimal, as it doesn't suffer from the unpredictability of the
BigDecimal(double) constructor.
Check this SO thread for why double results in a loss of precision.
As already pointed by the previous answers about double precision, the value here is very close to zero. You can see it with System.out.format as well.
System.out.format("%.14f%n",a+b+c+d);
System.out.format("%1.1f%n",a+b+c+d); //to print 0.0
Related
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 1 year ago.
I have a function that rounds a float to n number of digits using BigDecimal.setScale
private float roundPrice(float price, int numDigits) {
BigDecimal bd = BigDecimal.valueOf(price);
bd = bd.setScale(numDigits, RoundingMode.HALF_UP);
float roundedFloat = bd.floatValue();
return roundedFloat;
}
public void testRoundPrice() {
float numberToRound = 0.2658f;
System.out.println(numberToRound);
float roundedNumber = roundPrice(numberToRound, 5);
System.out.println(roundedNumber);
BigDecimal bd = BigDecimal.valueOf(roundedNumber);
System.out.println(bd);
}
Output:
0.2658
0.2658
0.26579999923706055
How can I prevent BigDecimal from adding all these extra digits at the end of my rounded value?
NOTE: I can't do the following, because I dont have access to the number of digits in the api call function.
System.out.println(bd.setScale(5, RoundingMode.CEILING));
It’s the other way around. BigDecimal is telling you the truth. 0.26579999923706055 is closer to the value that your float has got all the time, both before and after rounding. A float being a binary rather than a decimal number cannot hold 0.2658 precisely. Actually 0.265799999237060546875 is as close as we can get.
When you print the float, you don’t get the full value. Some rounding occurs, so in spite of the float having the aforementioned value, you only see 0.2658.
When you create a BigDecimal from the float, you are really first converting to a double (because this is what BigDecimal.valueOf() accepts). The double has the same value as the float, but would print as 0.26579999923706055, which is also the value that your BigDecimal gets.
If you want a BigDecimal having the printed value of the float rather than the exact value in it or something close, the following may work:
BigDecimal bd = new BigDecimal(String.valueOf(roundedNumber));
System.out.println(bd);
Output:
0.2658
You may get surprises with other values, though, since a float hasn’t got that great of a precision.
EDIT: you were effectively converting float -> double -> String -> BigDecimal.
These insightful comments by Dawood ibn Kareem got me researching a bit:
Actually 0.265799999237060546875.
Well, 0.26579999923706055 is the value returned by calling
toString on the double value. That's not the same as the number
actually represented by that double. That's why
BigDecimal.valueOf(double) doesn't in general return the same value
as new BigDecimal(double). It's really important to understand the
difference if you're going to be working with floating point values
and with BigDecimal.
So what really happened:
Your float internally had the value of 0.265799999237060546875 both before and after rounding.
When you are passing your float to BigDecimal.valueOf(double), you are effectively converting float -> double -> String -> BigDecimal.
The double has the same value as the float, 0.265799999237060546875.
The conversion to String rounds a little bit to "0.26579999923706055".
So your BigDecimal gets the value of 0.26579999923706055, the value you saw and asked about.
From the documentation of BigDecimal.valueOf(double):
Translates a double into a BigDecimal, using the double's
canonical string representation provided by the
Double.toString(double) method.
Links
Stack Overflow question: Is floating point math broken?
Documentation: BigDecimal.valueOf(double)
Stack Overflow question: BigDecimal - to use new or valueOf
I've decided to modify my program to use BigDecimal as the base type for my property price in my object instead of type float. Although tricky at first it is definitely the cleaner solution in the long run.
public class Order {
// float price; // old type
BigDecimal price; // new type
}
I want to substract 2 double values, and I have tried the following code.
double val1 = 2.0;
double val2 = 1.10;
System.out.println(val1 - val2);
and I got the output as,
0.8999999999999999
For getting output as 0.9 I tried with BigDecimal as follows,
BigDecimal val1BD = new BigDecimal(val1);
BigDecimal val2BD = new BigDecimal(val2);
System.out.println(val1BD.subtract(val2BD));
And I got the output as,
0.899999999999999911182158029987476766109466552734375
Then I tried with BigDecimal.valueOf()
val1BD = BigDecimal.valueOf(val1);
val2BD = BigDecimal.valueOf(val2);
System.out.println(val1BD.subtract(val2BD));
And finally I got the output as 0.9.
My question is what is the difference between case 2 & case 3?
In case 2 why I got the output like that?
BigDecimal.valueOf(double d) uses canonical String representation of double value, internally Double.toString(double) is used, that's why you are getting 0.9 in second case.
Note: This is generally the preferred way to convert a double (or
float) into a BigDecimal, as the value returned is equal to that
resulting from constructing a BigDecimal from the result of using
Double.toString(double).
While with new BigDecimal(0.9) it converts value to exact floating point representation of double value without using String representation,
Translates a double into a BigDecimal which is the exact decimal
representation of the double's binary floating-point value.
...
NOTES :
The results of this constructor can be somewhat unpredictable.
...
FOR EXAMPLE :
BigDecimal bd1 = new BigDecimal(Double.toString(0.9));
BigDecimal bd2 = new BigDecimal(0.9);
System.out.println(bd1);
System.out.println(bd2);
OUTPUT :
0.9
0.90000000000000002220446049250313080847263336181640625
Just for those others that got here looking for some other issue with BigDecimal(not related to the question above)...
remember to give a mathContext to the methods to avoid certain problems e.g.
MathContext mc = new MathContext(10, RoundingMode.HALF_UP);
BigDecimal hitRate = new BigDecimal(totalGetValuesHitted).divide(new BigDecimal(totalGetValuesRequested), mc);
BigDecimal missRate = new BigDecimal(1.0, mc).subtract(hitRate, mc);
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 7 years ago.
double x = 0.00090;
double b = 0.00100;
double c = x - b;
produces
-1.0000000000000005E-4
instead of
-0.0001
and
double x = -0.09;
double b = 0.001;
double c = x * b;
produces
-8.999999999999999E-5
instead of
-0.00009
I also tried with
Math.round(c) and Math.round(c*100.0)/100.0
but it is producing same results or results with incomplete number range after decimal.
That's how numeric operations are defined in the specification.
Decimal numbers are internally represented as the closest approximation, which in some cases is not the exact literal value.
If you need precise numeric computation, you have to use BigDecimal.
The answers are correct. You might want to read up on how doubles are stored in binary digits. its because it's base 2. If we used something like base 3, then in normal digits, 2/3 would be 0.66666666... but in the "tridigit" it would be 0.2
The E notation is confusing you (explanation on how it works here)
-1.0000000000000005E-4
is
-0.00010000000000000005
in standard notation and
-8.999999999999999E-5
is
-0.00008999999999999999
in standard notation. All the answer you see are correct (almost, but they are very close, decimal math isn't always precise), just using the E notation.
try this:
double x = 0.00090;
double b = 0.00100;
BigDecimal xd = new BigDecimal(x).setScale(10, RoundingMode.HALF_UP);
BigDecimal bd = new BigDecimal(b).setScale(10, RoundingMode.HALF_UP);
BigDecimal cd = xd.multiply(bd);
double c = cd.doubleValue();
System.out.println(c);
For precise calculations, like money calculations, you should use BigDecimals, because they have desired precision, and don't lost any accuracy.
If you prefer printing without "E", try this line:
System.out.println(cd.toPlainString());
I have below code:
Double a = new Double((123456798/1000000)); //123456798 this value comes from client side as a `int`
DecimalFormat df = new DecimalFormat("###.###");
log.info("a :"+a+" df "+df.format(a.doubleValue()));
output:
a :123.0 df 123
//i want output like this, a :123.xxx fd 123.xxx
please help
UPDATE:
123456798 this value comes from client side as a int so i cant do it as 123456798.0 (or something)
123456798 and 1000000 are int literals, so dividing them will use integer arithmetic, and yield 123.
Instead, you could use floating point literals in order to use floating point arithmetic:
Double a = new Double((123456798.0/1000000.0));
DecimalFormat df = new DecimalFormat("###.###");
log.info("a :"+a+" df "+df.format(a.doubleValue()));
Any one value in the division should be float or double.
Double a = new Double((123456798.0/1000000));
or
Double a = new Double((123456798/1000000.0));
if you are getting these values in variables, then multiply it with 1.0
like
Double a = new Double((variable*1.0/1000000));
Put it like that
Double a = new Double((123456798.0/1000000.0)); // <- note ".0"
the reason of the misbehavior is the integer division:
123456798/1000000
is the integer value, while
123456798.0/1000000.0
is the floating point one (double)
Double a = new Double((123456798/1000000));
You are doing integer division here. Make one of the constants a double, so that floating-point division is done. Also, why are you using Double? It's better to use the primitive type double.
double a = 123456798.0 / 1000000;
Or simply, since they are constants:
double a = 123.456789;
You perform an integer division, thats why a is incorrect:
Double a = new Double(123456798.0/1000000);
I'm not sure if I'm doing this right.
I'm doing scientific calculations that need to be accurate as possible so I am converting the existing use of Double to BigDecimal.
// before
double tmp = x - (y / z);
// after
BigDecimal tmp = new BigDecimal(
x.value().subtract(y.value().divide(z.value())).toString());
Is this logical or what?
You are doing your arithmetics with doubles before converting the result to BigDecimal. That way you don't gain any precision.
You should convert every number to BigDecimal as soon as possible and then use the methods of BigDecimals (subtract, divide and so on) on the BigDecimal representation to do the arithmetics.
BigDecimal bdX = new BigDecimal(x);
BigDecimal bdY = new BigDecimal(y);
BigDecimal bdZ = new BigDecimal(z);
BigDecimal tmp = bdX.subtract(bdY.divide(bdZ));
BigDecimal has methods for all the operators. You should use them instead. You can also control (specify) the scale and rounding.
Avoid using doulbles, instead use BigDecimal from the beginning.
Assuming that x, y and z are doubles
BigDecimal tmp = new BigDecimal(x).subtract(
new BigDecimal(y).divide(new BigDecimal(z), MathContext.DECIMAL64));
see BigDecimal.divide API to understand why to use MathContext