参见英文答案 > how does Java convert floats to strings 3个
正如许多地方(例如Why can’t decimal numbers be represented exactly in binary?)所解释的那样,并非所有小数部分都可以表示为浮点值(例如存储在Java中的浮点数中).
给出的典型示例是“0.2”.根据这个漂亮的IEEE 754 Converter,最接近0.2的浮点数约为0.20000000298023224,因此解析“0.2”作为浮点数应该产生这个结果.
但是,我注意到Java似乎能够做到这一点:
String number="0.2";
float f = Float.parseFloat(number);
System.out.println("Result of roundtrip String -> float -> String: "+f);
打印:
Result of roundtrip String -> float -> String: 0.2
Java如何知道我想要(舍入)输出“0.2”,而不是如上所述的精确输出“0.20000000298023224”?
Javadocs of Float.toString()
试着解释一下:
How many digits must be printed for the fractional part of m or a?
There must be at least one digit to represent the fractional part,and
beyond that as many,but only as many,more digits as are needed to
uniquely distinguish the argument value from adjacent values of type
float.
不幸的是,这让我更加困惑.为什么“打印尽可能多的数字来唯一区分参数值”允许Java打印“0.2”?
理想情况下,答案也可以解释为什么选择此打印算法.这个例子是(一些)往返工作吗?还有其他动机吗?