双数据类型不在java中返回所需的输出

时间:2014-08-11 20:12:35

标签: java double bigdecimal

在Java中,对于以下代码

Double d = 2.0-1.1;
System.out.println(d);

结果是

0.8999999999999999

如果该程序正在处理敏感信息,如先行/金钱或美分,我该如何解决这个问题?

我还尝试了以下代码:

new BigDecimal(d)

输出

0.899999999999999911182158029987476766109466552734375

对于上述情况,我应该怎么做才能得到0.90?

1 个答案:

答案 0 :(得分:2)

由于double无法准确表示2 - 1.11的结果,因此在使用构造函数时精度已经丢失。因此,您需要使用String based constructor链接BigDecimal

BigDecimal result = new BigDecimal("2").subtract(new BigDecimal("1.1"));

标准参考是What Every Computer Scientist Should Know About Floating-Point Arithmetic 更易于理解的阅读:Floating Point Numbers