BigDecimal添加错误的值 [英] BigDecimal adding wrong value

查看:125
本文介绍了BigDecimal添加错误的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个BigDecimal定义如下:

private static final BigDecimal sd = new BigDecimal(0.7d);

如果我打印出来,我会得到值:

if i print it, i get the value:

0.6999999999999999555910790149937383830547332763671875

这会导致一些错误的计算.有谁知道将0.7的准确值作为BigDecimal的方法?将其更改为0.71可以查看正确的结果,但是不应该这样

which causes some wrong calculations. Does anyone know a way to get the exact value of 0.7 as BigDecimal? Change it to 0.71 would view the right result, but it shouldn't be like that

推荐答案

使用字符串文字:

private static final BigDecimal sd = new BigDecimal("0.7");

如果您使用double,则实际上 public BigDecimal(double val) .您未获得0.7的原因是它不能用double精确表示.有关更多信息,请参见链接的JavaDoc.

If you use a double, actually public BigDecimal(double val) is called. The reason you do not get 0.7 is that it cannot be exactly represented by a double. See the linked JavaDoc for more information.

这篇关于BigDecimal添加错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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