根据几个浮点计算器以及下面的代码,下列 32 位 00111111010000000100000110001001 实际的浮点值为(0.750999987125396728515625)。由于它是实际的浮点数,我认为将其存储在 Double 或 Float 中会保留精度和确切值,只要 (1) 不执行任何运算,(2) 使用实际值,(3) 值不被 down-cast。那么为什么实际值与 casted(举例 1)和字面(举例 2)值 (0.7509999871253967) 不同呢?
我使用了此计算器作为示例: https://www.h-schmidt.net/FloatConverter/IEEE754.html
我使用了此计算器作为示例: https://www.h-schmidt.net/FloatConverter/IEEE754.html
import java.math.BigInteger;
import java.math.BigDecimal;
public class MyClass {
public static void main(String args[]) {
int myInteger = new BigInteger("00111111010000000100000110001001", 2).intValue();
Double myDouble = (double) Float.intBitsToFloat(myInteger);
String myBidDecimal = new BigDecimal(myDouble).toPlainString();
System.out.println(" bits converted to integer: 00111111010000000100000110001001 = " + myInteger);
System.out.println(" integer converted to double: " + myDouble);
System.out.println(" double converted to BigDecimal: " + myBidDecimal);
Double myDouble2 = 0.750999987125396728515625;
String myBidDecimal2 = new BigDecimal(myDouble2).toPlainString();
System.out.println("");
System.out.println(" Ignore the binary string: ");
System.out.println(" double from literal: " + myDouble2);
System.out.println(" double converted to BigDecimal: " + myBidDecimal2);
}
}
以下是输出结果:
bits converted to integer: 00111111010000000100000110001001 = 1061175689
integer converted to double: 0.7509999871253967
double converted to BigDecimal: 0.750999987125396728515625
Ignore the binary string:
double from literal: 0.7509999871253967
double converted to BigDecimal: 0.750999987125396728515625