Java – about the precision of float type
•
Java
I can't understand why
float f = Integer.MAX_VALUE; System.out.println(Integer.MAX_VALUE); System.out.println((int)f);
Produce the same line,
And why
Float f2 = (float) Integer.MAX_VALUE; System.out.println(Integer.MAX_VALUE); System.out.println(f2.intValue());
I mean, the mantissa length of a floating point number is 2 ^ 23-1 How does it try to keep the max of an integer_ Value, i.e. 2 ^ 31 – 1?
Solution
It doesn't actually The value of F is 2147483648
However, narrowing primitive conversion clamps this value from float to int It reaches this part:
You can easily see this by making the number bigger:
float f = Integer.MAX_VALUE; f = f * 1000; System.out.println(Integer.MAX_VALUE); // 2147483647 System.out.println((int)f); // 2147483647
Or by casting instead, it is obviously not necessary to clamp at the same point:
float f = Integer.MAX_VALUE; System.out.println(Integer.MAX_VALUE); // 2147483647 System.out.println((long)f); // 2147483648
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码