Java float vs double precision

时间:2017-11-13 06:20:00

标签: java floating-point double precision

public class MyClass {
    public static void main(String args[]) {
        float x=2.0f;
        float y=1.1f;

        System.out.println("Float = " + (x - y));

        double a=2.0d;
        double b=1.1d;

        System.out.println("Double = " + (a - b));
    }
}

Answer:

Float = 0.9
Double = 0.8999999999999999

I understand if I want better precision, I should have used BigDecimal, but why float (which is 32 bit with lesser precision compare to double) doesn't encounter the rounding issue?

1 个答案:

答案 0 :(得分:1)

我修改了代码,以便在舍入值后立即打印每个结果的确切值:

Float = 0.9
0.89999997615814208984375
Double = 0.8999999999999999
0.899999999999999911182158029987476766109466552734375

双重结果比浮动结果更接近0.9。这些是在任何其他计算中使用的值。

打印输出的差异是Float和Double toString方法的结果。每个都旨在产生最短的结果,在转换回相应的类型时,将产生原始值。在浮点解析时,0.9将转换为0.89999997615814208984375。它将在双重解析时转换为0.90000000000000002220446049250313080847263336181640625。唯一标识double的位数需要更多位数而不是浮点数。