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

Vin*_*ins 0 java math

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

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

输出是 Hello the calculated value of a=0.030000687

但我想要a=0.030000000哪个是完美的价值.

Buh*_*ndi 6

浮点运算,开发人员应该知道的.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)