简体   繁体   English

java float转换为字符串给出不同的结果

[英]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. 您必须考虑floatdouble类型处理浮点数 :这意味着它们必须在整数和小数部分之间分配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: 你遇到的问题来自两个事实:

  • Too much digits in the integer part. 整数部分中的位数太多。
  • Using float. 使用浮动。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM