double值是如何存储在JVM中的,JVM是如何从内存中读出其对应的二进制值并转换为十进制值的?
How double value is stored in JVM and how JVM read out its corresponding binary value from memory and cast it to decimal value?
我们知道,如果要在JVM中存储一个十进制值,如2.4,首先要将其转换成二进制值。但是对于它的转换逻辑来说,它不能转换出精确的值2.4,它转换后的二进制值大约是2.3999999999999999。
public class Application {
public static void main(String[] args) {
double d = 2.4;
System.out.println(d);
}
}
我猜,JVM 将这个值存储在内存中。但是虽然System.out.println(d);
,我认为首先应该从内存中获取二进制值,然后打印它。我认为它从内存中得到的是 2.3999999999999999,这里它打印出 2.4。
有人能说出区别吗?非常感谢!
println
在内部使用 Double.toString
将双精度数转换为字符串,然后可以打印。
Double.toString
javadoc 表示如下:
How many digits must be printed for the fractional part of m or a?
There must be at least one digit to represent the fractional part, and
beyond that as many, but only as many, more digits as are needed to
uniquely distinguish the argument value from adjacent values of type
double. That is, suppose that x is the exact mathematical value
represented by the decimal representation produced by this method for
a finite nonzero argument d. Then d must be the double value nearest
to x; or if two double values are equally close to x, then d must be
one of them and the least significant bit of the significand of d must
be 0.
这里的重要部分是"as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double"。
这意味着只要 2.4
比任何其他可能的双精度值更接近 d
中的实际值,就会打印 2.4
。
我们知道,如果要在JVM中存储一个十进制值,如2.4,首先要将其转换成二进制值。但是对于它的转换逻辑来说,它不能转换出精确的值2.4,它转换后的二进制值大约是2.3999999999999999。
public class Application {
public static void main(String[] args) {
double d = 2.4;
System.out.println(d);
}
}
我猜,JVM 将这个值存储在内存中。但是虽然System.out.println(d);
,我认为首先应该从内存中获取二进制值,然后打印它。我认为它从内存中得到的是 2.3999999999999999,这里它打印出 2.4。
有人能说出区别吗?非常感谢!
println
在内部使用 Double.toString
将双精度数转换为字符串,然后可以打印。
Double.toString
javadoc 表示如下:
How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0.
这里的重要部分是"as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double"。
这意味着只要 2.4
比任何其他可能的双精度值更接近 d
中的实际值,就会打印 2.4
。