[英]java float conversion to string giving different result
why below java code prints different value (decimal part) of same float variable? 为什么下面的java代码打印相同浮点变量的不同值(小数部分)?
public static void main(String[] args) {
float f = 2001797.11f;
System.out.println(String.format("%013.2f", f));
System.out.println(Float.toString(f));
System.out.println(String.format("%018.5f", f));
}
Output: 输出:
0002001797.13
2001797.1
000002001797.12500
The confusion stems from the line float f = 2001797.11f;
混乱源于
float f = 2001797.11f;
线float f = 2001797.11f;
. 。 The closest
float
to the mathematical value "2001797.11"
is actually 2001797.125
. 最接近数学值
"2001797.11"
float
实际上是2001797.125
。 You can see this by doing 你可以这样看
System.out.println(new BigDecimal(2001797.11f));
So, f
is actually 2001797.125
and the 2 uses of String.format
have rounded correctly. 因此,
f
实际上是2001797.125
并且String.format
的2次使用已正确舍入。
So why doesn't Float.toString(f)
produce "2001797.125"
? 那么为什么
Float.toString(f)
不会产生"2001797.125"
? It's because Float.toString
only displays enough decimal places in order to distinguish the value from other float
s. 这是因为
Float.toString
只显示足够的小数位数,以便将值与其他float
值区分开来。 In this case, just displaying the 1
after the decimal place is enough. 在这种情况下,只显示小数位后的
1
。
You must consider that float
and double
types handle floating point numbers: This means that they have to distribute its 32 or 64 bits between the integer and the decimal part. 您必须考虑
float
和double
类型处理浮点数 :这意味着它们必须在整数和小数部分之间分配32位或64位。
And so: The most digits in the integer part, the most bits will be dedicated to them, and the less bits to the decimal part. 所以:整数部分中的最多位数,大多数位将专用于它们,小数部分的位数越少。 So, the decimal part will be less accurate .
因此,小数部分将不太准确 。
The problem you are suffering comes from two facts: 你遇到的问题来自两个事实:
If you need more precission (according to the scale of values your program must handle), you should migrate to double
. 如果您需要更多精确度(根据程序必须处理的值的大小),您应该迁移到
double
。 And if you want infinite precission, to BigDecimal
. 如果你想要无限期,那就是
BigDecimal
。
String.format
使用显式格式规则,而Float.toString(float n)
使用文档中描述的算法: http : //docs.oracle.com/javase/7/docs/api/java/lang/Float.html#的toString(浮点)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.