我最近阅读了很多有关浮点表示的内容(包括:How To Represent 0.1 In Floating Point Arithmetic And Decimal)。
现在我知道0.1不能正确表示,当我这样做时:

System.out.println(2.0f - 1.9f);

我永远不会得到准确的结果。

所以问题是:
如何在以下代码中表示0.1f以便正确打印0.1?
那是某种合成糖吗?
在我上面提到的文章中:0.1在内存中表示为0.100000001490116119384765625。那么为什么我没有得到此代码的输出:
System.out.println(0.1f);

Java如何处理呢?

最佳答案

System.out.println对浮点数和 double 数进行四舍五入。它使用了Float.toString(),它本身(在oraclew JDK中)委托(delegate)给FloatingDecimal类-您可以查看the source of FloatingDecimal#toJavaFormatString() 以获得更多细节。

如果你试试:

BigDecimal bd = new BigDecimal(0.1f);
System.out.println(bd);

您将看到0.1f的实际值:0.100000001490116119384765625。

07-24 09:45
查看更多