【问题标题】:Unexpected decimal result意外的十进制结果
【发布时间】:2011-05-20 17:14:34
【问题描述】:

我运行了以下代码,但没想到会出现这样的结果..

public class SampleDemo {
    public static void main(String args[]) {  
        System.out.println(10.00 - 9.10);
    }
}

我得到 o/p 为 0.9000000000000004

为什么会这样?

【问题讨论】:

标签: java floating-point decimal


【解决方案1】:

这是因为十进制值不能用 float 或 double 精确表示。

一个建议:在需要准确答案的地方避免使用 float 和 double。改用 BigDecimal、int 或 long


使用 int :

public class SampleDemo {
    public static void main(String args[]) {  
        System.out.println(10 - 9);
    }
}

// Output : 1

使用 BigDecimal:

import java.math.BigDecimal;

public class SampleDemo {
  public static void main(String args[]) {
     System.out.println(new BigDecimal("10.00").subtract(new BigDecimal("9.10")));
                             }
                     }
// Output : 0.90

【讨论】:

  • 只是指出,如果您需要这种精度,请选择BigDecimal,它可以让您更好地控制精度、规模、四舍五入等。
  • 是的,@Anthony +1 我将其添加到我的答案中。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-05
  • 2014-10-14
  • 1970-01-01
  • 1970-01-01
  • 2017-03-15
相关资源
最近更新 更多