java - 打印带有更多小数点的 float

标签 java floating-point decimal

当我尝试打印具有更多小数点的 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/

相关文章:

java - 如何正确使用 `HTMLEditorKit.insertHTML()` ?

c# - 十进制不能做什么,但双倍可以,反之亦然?

python - decimal.Decimal(n) % 1 返回 InvalidOperation, DivisionImpossible for all n >= 100

c - C中的 float

c - 将尾数作为位返回

python - 以工程格式打印编号

c++ - 该标准是否定义了共同基础?

java - 什么是NullPointerException,我该如何解决?

java - Java中的骑士之旅(递归)

java - 如何使用PDFBox向PDF添加背景图像?