I have a smple sop line as :
System.out.println(0.0000877979+0.3067846127);
The output of above line is : 0.30687241060000003
But the expected is : 0.3068724106
I doubt,how come extra 0000003
at last came.
I have a smple sop line as :
System.out.println(0.0000877979+0.3067846127);
The output of above line is : 0.30687241060000003
But the expected is : 0.3068724106
I doubt,how come extra 0000003
at last came.
You need to understand what a double
number is: it's a binary floating point number. As such, it can't represent all decimal numbers exactly. For example, take the number 0.2. There's no finite binary representation of that - just as there isn't a finite decimal representation of 1/3.
If you're interested in decimal digits then you should use BigDecimal
. However, that may not actually be appropriate for what you're trying to achieve. What do the numbers mean in your case? Are they measured values from natural properties (weight, height etc) or are they "artificial", naturally decimal values such as financial ones? This affects which type you should use.
BigDecimal
is different from double
in three important ways:
When constructing a BigDecimal
, it's important that you start with accurate values - converting a double
to BigDecimal
is almost always a mistake. So if you've got user input as text, that's fine:
BigDecimal bd1 = new BigDecimal("0.0000877979");
BigDecimal bd2 = new BigDecimal("0.3067846127");
System.out.println(bd1.add(bd2)); // Prints 0.3068724106
In other cases you may start with another BigDecimal
, or possibly an integer.
This is because of using floating-point arithmetic in a binary environment. Look at this IEEE 754 standard for more information.
You should use BigDecimal class for pecision.
Use BigDecimal.valueOf(value) to convert the double
to BigDecimal
.
Translates a double into a BigDecimal, using the double's canonical string representation provided by the Double.toString(double) method.
This is normal due to the limited nature of floating point numbers (float
and double
in Java). Please learn about floating point arithmetics (IEEE 754).
To get exact numbers use BigDecimal
in Java.
BigDecimal bd = new BigDecimal(0.0000877979);
BigDecimal bd1 = new BigDecimal(0.3067846127);
System.out.print(bd.add(bd1).setScale(10,0));
To get the exact result, you can try like this,
BigDecimal b1= BigDecimal.valueOf(0.0000877979);
BigDecimal b2= BigDecimal.valueOf(0.3067846127);
System.out.println(b1.add(b2));