即使精度超过可用数字,格式也不会打印所有两位数

时间:2017-11-08 18:12:37

标签: java double precision number-formatting bigdecimal

我无法绕过这个。

似乎JDK的数字格式化例程即使给定足够的精度字段也无法打印两位数。

特别是,我不明白为什么以下程序的第二个输出行是:

  

b.doubleValue() => 34981.29000000000000000000000000000000000000000000000000

我认为打印的价值应为34981.29000000000087311491370201110839843750000000000000

你能帮助我理解为什么会这样吗:

PrecisionLoser.java

import java.math.BigDecimal;

public class PrecisionLoser {
    public static void main(final String[] args) {
        final BigDecimal b = new BigDecimal("34981.29");
        System.out.printf("b                => %.50f%n", b);
        System.out.printf("b.doubleValue()  => %.50f%n", b.doubleValue());
        System.out.printf("b.floatValue()   => %.50f%n", b.floatValue());
        System.out.printf("Double.MIN_VALUE =>     %.50f%n", Double.MIN_VALUE);
        System.out.println("-");
        final double d = 34981.2900000000008731149137020111083984375;
        System.out.printf("d                               => %.50f%n", d);
        System.out.printf("new BigDecimal(d)               => %.50f%n", new BigDecimal(d));
        System.out.printf("new BigDecimal(b.doubleValue()) => %.50f%n", new BigDecimal(b.doubleValue()));
        System.out.printf("d == b.doubleValue()            => %b%n", d == b.doubleValue());
        final double e = 34981.29;
        System.out.printf("d == e                          => %b%n", d == e);
        System.out.println("-");
        System.out.printf("Double.doubleToLongBits(b.doubleValue()) => 0x%16x%n", Double.doubleToLongBits(b.doubleValue()));
        System.out.printf("Double.doubleToLongBits(d)               => 0x%16x%n", Double.doubleToLongBits(d));
        System.out.printf("Double.doubleToLongBits(e)               => 0x%16x%n", Double.doubleToLongBits(e));
    }
}

输出

$ javac PrecisionLoser.java
$ java PrecisionLoser
b                => 34981.29000000000000000000000000000000000000000000000000
b.doubleValue()  => 34981.29000000000000000000000000000000000000000000000000
b.floatValue()   => 34981.28906250000000000000000000000000000000000000000000
Double.MIN_VALUE =>     0.00000000000000000000000000000000000000000000000000
-
d                               => 34981.29000000000000000000000000000000000000000000000000
new BigDecimal(d)               => 34981.29000000000087311491370201110839843750000000000000
new BigDecimal(b.doubleValue()) => 34981.29000000000087311491370201110839843750000000000000
d == b.doubleValue()            => true
d == e                          => true
-
Double.doubleToLongBits(b.doubleValue()) => 0x40e114a947ae147b
Double.doubleToLongBits(d)               => 0x40e114a947ae147b
Double.doubleToLongBits(e)               => 0x40e114a947ae147b

1 个答案:

答案 0 :(得分:1)

用调试器查看转换过程,我认为会发生的事情是首先将double转换为字符串,忽略精度。然后,调整字符串以匹配指定的精度(在末尾用0填充,或用舍入截断 - 参见sun.misc.FormattedFloatingDecimal的applyPrecision)。

并且,如果重新解析,原始转换似乎使用将产生原始double值的(最小的?)十进制数字。