< 2006年9月 >
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

# 相册

•

### 评论排行榜

2006 913 星期三

System.out.println( 1.03   -  . 42 ); // 答案是0.6100000000000001 ！

System.out.println(
1.00   -   9 * . 10 ); // 答案是0.09999999999999995 ！

BigDecimal int 或者 long

BigDecimal bd  =   new  BigDecimal( " 1.00 " );

Wednesday, September 13, 2006

Don’t use float and double when exact answers are required

What? Aren’t calculating decimal are what they are design for? I made such an ignorant question when I first read effective java-item31.

The phenomenon:

Why we can’t use float and double to calculate decimal when exact results are required?

Try the following statements:

System.out.println( 1.03   -  . 42 ); // the answer is 0.6100000000000001 ！

System.out.println(
1.00   -   9 * . 10 ); // the answer is 0.09999999999999995 ！

You will find the answers are not agree with what you have learned in primary school.

The reason:

It is all because float and double can not represent exactly 0.1, or any other negative power of ten. They are designed for scientific and engineering calculation which demands accurate approximation. And they are ill-suited for monetary calculations.

The solution:

Use BigDecimal, int or long instead.

BigDecimal bd  =   new  BigDecimal( " 1.00 " );

Transfer all decimal numbers involved in the calcution into BigDecimal objects as above, and then use them to calcute for a exact result, following with two disadvantages, the first, obviously, less convenient than using primitive types, all notations like +,-,*,/ can not be applied neither; the second, it will be slower, which can be ignored if it was not used in a heavily repeated loop. But you also get one merit which comes from the fact that BigDecimal carrys quite a lot of rounding methods.

If the quantity is not big, you can use int or long instead, you surely understand how to implement the idea. In performance critical section, and you don’t mind keeping track the of the decimal point yourself, this is feasible. But you have not choice if the quantity is over 18 digits, only BigDecimal is available.

posted on 2006-09-13 19:23 Ye Yiliang 阅读(8710) 评论(4)  编辑  收藏 所属分类: Java

FeedBack:
# re: 不要用float和double来进行精确的小数计算 2006-09-14 00:21 weide

# re: 不要用float和double来进行精确的小数计算 2006-09-14 08:42 Flyingis
@weide
Decimal的构造方法应该可以直接设定有效位数啊。

# re: 不要用float和double来进行精确的小数计算 2006-09-14 13:06 lgn21st
《Java Puzzle》上面开篇就提到这个puzzle!  回复  更多评论

# re: 不要用float和double来进行精确的小数计算 2006-09-14 18:54 冰川

 只有注册用户登录后才能发表评论。 网站导航: 相关文章: