为什么Java在浮点计算后会显示额外的值?

我在下面有一段非常简单的代码,我认为从用户的角度给出了错误的结果。

package com.test.sample; public class Test { public static void main(String[] args) { float c,d; c = (float) 12.47; d = (float) 12.44; d = c - d; System.out.println("Hello the calculated value of a=" + d); } } 

输出为Hello the calculated value of a=0.030000687

但我想要a=0.030000000 ,这是一个完美的价值。

浮点运算 ,开发人员应该知道什么。

JVM实现了IEEE-754 1985浮点标准,并且它具有精度问题 (因为浮点数不能精确地表示所有实数)。

如果您寻求准确性,请改用java.math.BigDecimal对象。


更新:这是我采用您的示例并使用BigDecimal实现预期结果的方式:

 import java.math.BigDecimal; /** * @author The Elite Gentleman * */ public class BigDecimalTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BigDecimal a = new BigDecimal(Float.toString(12.47f)); BigDecimal b = new BigDecimal(Float.toString(12.44f)); BigDecimal c = a.subtract(b); System.out.println(c); } }