java float 向double 隐式转换精度会有丢失
float f = 8.69f;
int a = Float.floatToIntBits(f);
String floatStr = Integer.toBinaryString(a);
double d1 = f;
long b = Double.doubleToLongBits(d1);
String convertStr = Long.toBinaryString(b);
double d2 = 8.69d;
long c = Double.doubleToLongBits(d2);
String doubleStr = Long.toBinaryString(c);
System.out.println(floatStr);
System.out.println(convertStr);
System.out.println(doubleStr);
输出为
1000001000010110000101000111101 100000000100001011000010100011110100000000000000000000000000000 100000000100001011000010100011110101110000101000111101011100001
想问下,为什么在隐式转换的过程中,jvm只是单纯的拷贝float中的尾数部分,然后补0,而不是精确的计算尾数部分的值?
ringa_lee2017-04-18 09:20:28
There is no loss of precision when adding 0 to the mantissa, this is how floating point numbers are represented
PHP中文网2017-04-18 09:20:28
float occupies 4 bytes, while double occupies 8 bytes.
During the memory copy process, only 4 bytes are copied in, and the remaining bytes default to 0. (This is not necessarily the case in release mode and debug mode.)