为什么java的BigDecimal也无法精准计算double类型吗?

qccxw 生活常识评论111字数 923阅读模式

不要使用double来构造一个BigDcimal对象。BigDecimal的构造函数有这么一段说明:

The results of this constructor can be somewhat unpredictable. One might assume that writing in Java creates a which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.The constructor, on the other hand, is perfectly predictable: writing creates a which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.由于double本身是不精确的,如果使用double作为构造函数参数,也会导致BigDecimal对象不精确,比如使用浮点数0.1来构造一个BigDecimal对象,它的实际值为 0.1000000000000000055511151231257827021181583404541015625,所以,需要精确计算的场景,推荐使用String类型的构造函数。文章源自玩技e族-https://www.playezu.com/127488.html

总之,在需要精确浮点数计算的场景,不要在任何地方使用double,float类型的变量,应该使用String类型来创建BigDecimal.文章源自玩技e族-https://www.playezu.com/127488.html

文章源自玩技e族-https://www.playezu.com/127488.html文章源自玩技e族-https://www.playezu.com/127488.html
玩技站长微信
添加好友自动发送入群邀请
weinxin
rainbow-shownow
玩技官方公众号
官方微信公众号
weinxin
PLAYEZU
 
  • 版权提示:本站仅供存储任何法律责任由作者承担▷诈骗举报◁▷新闻不符◁▷我要投稿◁
    风险通知:非原创文章均为网络投稿真实性无法判断,侵权联系2523030730
    免责声明:内容来自用户上传发布或新闻客户端自媒体,切勿!切勿!切勿!添加联系方式以免受骗。
  • 原创转载:https://www.playezu.com/127488.html
    转载说明: 点我前往阅读>>>
匿名

发表评论

匿名网友
确定