Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java double precision [duplicate]

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

like image 888
yodhevauhe Avatar asked Dec 02 '25 08:12

yodhevauhe


2 Answers

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

like image 60
ᅙᄉᅙ Avatar answered Dec 04 '25 01:12

ᅙᄉᅙ


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.

like image 20
AlexR Avatar answered Dec 04 '25 02:12

AlexR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!