BigDecimal/double Precision-数字四舍五入 [英] BigDecimal/double Precision - number rounds up higher

查看:99
本文介绍了BigDecimal/double Precision-数字四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的第二个方法调用setYCoordinate()会得到错误的值-89.99999435599995,而不是-89.99999435599994.

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

第一次调用setXCoordinate()会获得正确的值29.99993874900002.

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

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

我在BigDecimal.valueOf()内放置一个断点-该方法的代码如下-

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));
    }

在检查时,valueOf即"double val"本身收到的参数为-89.99999435599995.为什么?我在Maven pom.xml中设置了如下的Java版本

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>

推荐答案

因为 double 不能保持那么高的精度;初始化 BigDecimal 时,您不应该使用 double ,而应使用 String :

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");

请参阅:浮点数学运算是否被破坏?

这篇关于BigDecimal/double Precision-数字四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆