简体   繁体   中英

java float conversion to string giving different result

why below java code prints different value (decimal part) of same float variable?

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; . The closest float to the mathematical value "2001797.11" is actually 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.

So why doesn't Float.toString(f) produce "2001797.125" ? It's because Float.toString only displays enough decimal places in order to distinguish the value from other float s. In this case, just displaying the 1 after the decimal place is enough.

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.

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 . And if you want infinite precission, to BigDecimal .

String.format使用显式格式规则,而Float.toString(float n)使用文档中描述的算法: http//docs.oracle.com/javase/7/docs/api/java/lang/Float.html#的toString(浮点)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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