double的范围是-1023~1024,那整数范围大于这个区间的数,为了保持小数位的精度,该怎么计算呢。
本人刚开始学习Java,恳请各位DL指点。
你好。对精度要求比较高,可以使用BigDecimal,如下:
public class TestMain {
public static void main(String[] args) {
BigDecimal result = new BigDecimal("5000.123").add(new BigDecimal("132.123123"));
}
}
result就是计算的结果。
用BigDecimal,可以指定精度
在Java语言中,浮点数值分2种:float、double,均是带符号整型。
了解基本数据类型看这里:java有哪8种基本数据类型
这些类型除了长度不一致外,其他规则均按照以上规则,具体如下:
float
内存中占用8个字节,32bit。其中符号位1位,指数位8位,尾数位23位。指数偏差值:2^(8-1)-1 = 127
例如:
public class Test {
public static void main(String[] args) throws UnsupportedEncodingException {
float f1 = 423.1594f;
float f2 = -423.1594f;
int floatToIntBits1 = Float.floatToIntBits(f1);// 根据IEEE754规则,得到浮点的表示值。
int floatToIntBits2 = Float.floatToIntBits(f2);
System.out.println("正float===" + Integer.toBinaryString(floatToIntBits1));// 转二进制
System.out.println("负float===" + Integer.toBinaryString(floatToIntBits2));
System.out.println("正float===" + Integer.toHexString(floatToIntBits1));// 转十六进制
System.out.println("负float===" + Integer.toHexString(floatToIntBits2));
}
}
结果如下:
正float===1000011110100111001010001100111
负float===11000011110100111001010001100111
正float===43d39467
负float===c3d39467
double
内存中占用16个字节,64bit。其中符号位1位,指数位11位,尾数位52位。指数偏差值:2^(8-1)-1 = 1023
例如:
public class Test {
public static void main(String[] args) throws UnsupportedEncodingException {
double d1 = 423453.1597824345;
double d2 = -423453.1597824345;
long doubleToLongBits1 = Double.doubleToLongBits(d1);// 根据IEEE754规则,得到浮点的表示值。
long doubleToLongBits2 = Double.doubleToLongBits(d2);
System.out.println("正double===" + Long.toBinaryString(doubleToLongBits1));// 转二进制
System.out.println("负double===" + Long.toBinaryString(doubleToLongBits2));
System.out.println("正double===" + Long.toHexString(doubleToLongBits1));// 转十六进制
System.out.println("负double===" + Long.toHexString(doubleToLongBits2));
}
}
结果如下:
正double===100000100011001110110000111010010100011100111100000000110101011
负double===1100000100011001110110000111010010100011100111100000000110101011
正double===4119d874a39e01ab
负double===c119d874a39e01ab