2

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

Community
  • 1
  • 1
yodhevauhe
  • 765
  • 3
  • 11
  • 33

2 Answers2

7

If you need arbitrarily good precision, use the java.math.BigDecimal class.

P Varga
  • 19,174
  • 12
  • 70
  • 108
6

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.

AlexR
  • 114,158
  • 16
  • 130
  • 208