System.out.println((int)(99.9999999999999));
返回 99
System.out.println((int)(99.999999999999999999999999999999999999999));
返回 100
你能解释一下为什么吗?
最佳答案
double
文字 99.9999999999999
可以表示为小于 100
的 double
,因此强制转换to int
截断小数部分,99
是结果。
double
字面值 99.99999999999999999999999999999999999999
具有最接近 100
的实际值,转换为 int
很简单 100
这里。
System.out.println(99.9999999999999);
System.out.println((int)(99.9999999999999));
System.out.println(99.9999999999999 == 100.0);
System.out.println(99.999999999999999999999999999999999999999);
System.out.println((int)(99.999999999999999999999999999999999999999));
System.out.println(99.999999999999999999999999999999999999999 == 100.0);
我在这里使用 100.0
作为 double
文字,比较 2 个 double
值以查看它们是否完全相同 double
值。
打印出来:
99.9999999999999
99
false
100.0
100
true
JLS, Section 3.10.2涵盖浮点文字:
The details of proper input conversion from a Unicode string representation of a floating-point number to the internal IEEE 754 binary floating-point representation are described for the methods valueOf of class Float and class Double of the package java.lang.
Otherwise, s is regarded as representing an exact decimal value in the usual "computerized scientific notation" or as an exact hexadecimal value; this exact numerical value is then conceptually converted to an "infinitely precise" binary value that is then rounded to type double by the usual round-to-nearest rule of IEEE 754 floating-point arithmetic, which includes preserving the sign of a zero value.
(强调我的)
也就是说,该值被四舍五入以产生实际的 double
值。
关于java - 如何在 Java 中将 double 轮次显式转换为 int 轮次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23227191/