BigDecimal/double Precision - number rounds up higher

jerry.pepper :

The second of below method calls, to setYCoordinate(), gets incorrect value -89.99999435599995 instead of -89.99999435599994.

The first call to setXCoordinate() gets correct value 29.99993874900002.

setXCoordinate(BigDecimal.valueOf(29.99993874900002))
setYCoordinate(BigDecimal.valueOf(-89.99999435599994))

I put a breakpoint inside BigDecimal.valueOf() - this method's code looks as below -

public static BigDecimal valueOf(double val) {
        // Reminder: a zero double returns '0.0', so we cannot fastpath
        // to use the constant ZERO.  This might be important enough to
        // justify a factory approach, a cache, or a few private
        // constants, later.
        return new BigDecimal(Double.toString(val));
    }

The argument received by valueOf i.e. "double val" itself is -89.99999435599995 when inspected. Why? I have Java version set as below in my Maven pom.xml

<java.version>1.8</java.version>
Jacob G. :

Because a double can't retain that much precision; you shouldn't use a double, but rather a String when initializing your BigDecimal:

new BigDecimal("29.99993874900002");
new BigDecimal("-89.99999435599994");

See: Is floating point math broken?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111776&siteId=1