当我尝试打印具有更多小数点的 float 时,我遇到了非常奇怪的行为。
Float price = Float.valueOf("1602.72");
System.out.println(price); //prints 1602.72
outputValue = String.format("%.6f", price);
System.out.println(outputValue); //prints 1602.719971
我也使用了下面的代码,但得到了相同的结果
DecimalFormat df = new DecimalFormat("0.000000");
System.out.println(df.format(price)); //prints 1602.719971
我期望输出值为 1602.720000
(小数点后 6 位,带有额外的零)
最佳答案
float
是数字的二进制表示形式( 1/2 ^^ ? )
喜欢:
1/2^1 = 0.5,
1/2^2 = 0.25,
1/2^3 = 0.125,
1/2^4 = 0.0625, ...
结果是通过添加这些二进制数来呈现的,以找到最接近的匹配。
关于java - 打印带有更多小数点的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55062514/