Java之浮点运算

Java中的浮点数计算主要涉及float和double,他们都采用IEEE754标准,实际上是用利用科学计数法来表达实数。实数表示分为三个域: 

第一个域为符号域,0 表示数值为正数,而 1 则表示负数; 

第二个域为指数域,指数部分。其中单精度数为 8 位,双精度数为 11 位。float单精度的指数范围为-127 和 127 之间。 

第三个域为尾数域,其中单精度数为 23 位长,双精度数为 52 位长。

float用32bit存储,double用64bit存储。 double成为双精度:

double和float的区别:

1.double精度比较高,但是计算速度慢

2.原则是能用float的时候别用double

由于他们采用的是科学计数法来表述的,因此对计算要求比较高的地方不能采用直接double和float计算,建议采用BigDecimal,且必须用string去构造

举例如下:

public static void main(String[] args) {
	BigDecimal b1 = new BigDecimal("0.9");
	BigDecimal b2 = new BigDecimal("9");
	System.out.println(b1.multiply(b2).toString());
	double d1 = 0.9;
	double d2 = 9;
	System.out.println(d1 * d2);
	float f1 = 0.9f;
	float f2 = 9f;
	System.out.println(f1 * f2);

}

输出为:

8.1
8.1
8.099999

我们看到了float已经成无限接近了,但是满足不了需求。我们修改下测试case:

public static void main(String[] args) {
	BigDecimal b1 = new BigDecimal("0.009");
	BigDecimal b2 = new BigDecimal("9");
	System.out.println(b1.multiply(b2).toString());
	double d1 = 0.009;
	double d2 = 9;
	System.out.println(d1 * d2);
	float f1 = 0.009f;
	float f2 = 9f;
	System.out.println(f1 * f2);

}

输出结果变为:

0.081
0.08099999999999999
0.081

double已经变成无限接近了

上述具体造成的原因查阅相关文档。

切记:

在计算的时候为了保证精度需要用BigDecimal,且需要用string的构造去构造

猜你喜欢

转载自snv.iteye.com/blog/2215931