java double precision
10,173
Solution 1
If you need arbitrarily good precision, use the java.math.BigDecimal
class.
Solution 2
It is not a problem. It is how double works. You do not have to handle it and care about it. The precision of double is enough. Think, the difference between you number and the expected result is in the 19 position after decimal point.
The only conclusion from this fact is never try to compare floating point values using ==
- the results may be confusing.
Author by
yodhevauhe
Updated on June 04, 2022Comments
-
yodhevauhe almost 2 years
Possible Duplicate:
Precision of Floating Pointdouble a=0.000001,b=50000; b=a*b; System.out.println("double:"+b); // -> double:0.049999999999999996 float a=0.000001f,b=50000; b=a*b; System.out.println("float"+b); // -> float0.05
I have used double in most part of my code and today I found this problem. How should I handle this?
Context:
double []refValues= {100,75,50,25,15,5,1}; double bInMilliGram=b*1000; double pickedVal=0; for(double ref:refValues) if(ref<=bInMilliGram) { pickedVal=ref; break; } System.out.println("bInMilliGram:"+bInMilliGram+", pickedVal:"+pickedVal);
o/p: -> bInMilliGram:49.99999999999999, pickedVal:25.0