2007-10-13
要求精确答案就避免使用double和float
转载
今天看Effective java中有这么一条"如果要求精确答案,请避免使用float和double".
这可真让我大吃一惊!!我很不解,而且不是很相信.于是我写了两个个程序试验了下.
1
public class TestFloatDouble
{
2
3
public static void main(String[] args)
{
4
5
float a = (float) 1.03;
6
float b = (float) .42;
7
8
double c = 1.03;
9
double d = .42;
10
11
System.out.println(a * b);
12
System.out.println(c - d);
13
}
14
15
}

public class TestFloatDouble
{2

3

public static void main(String[] args)
{4

5
float a = (float) 1.03;6
float b = (float) .42;7
8
double c = 1.03;9
double d = .42;10
11
System.out.println(a * b);12
System.out.println(c - d);13
}14

15
}输出结果为
0.43259996
0.6100000000000001
而正确结果应为
0.4326
0.61
如果需要得到精确答案,那就用java.math里的BigDecimal吧,虽然效率相对低一点,但至少是正确的!!!
1
import java.math.BigDecimal;
2
3
public class TestBigDecimal
{
4
5
public static void main(String[] args)
{
6
7
BigDecimal a = new BigDecimal("1.03");
8
BigDecimal b = new BigDecimal(".42");
9
10
System.out.println(a.multiply(b));
11
System.out.println(a.subtract(b));
12
13
}
14
15
}
import java.math.BigDecimal;2

3

public class TestBigDecimal
{4

5

public static void main(String[] args)
{6

7
BigDecimal a = new BigDecimal("1.03");8
BigDecimal b = new BigDecimal(".42");9
10
System.out.println(a.multiply(b));11
System.out.println(a.subtract(b));12
13
}14

15
}输出结果同样也是正确结果为
0.4326
0.61







评论排行榜