Possible Duplicate:
Precision of Floating Point
double 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
If you need arbitrarily good precision, use the java.math.BigDecimal class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With