Type float or double to perform monetary calculations

本文探讨了在货币计算中使用浮点数可能导致的精度问题,并提供了使用BigDecimal、int或long进行精确计算的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/*

Do not use variables of type float or double to perform monetary calculations. The imprecision
of floating-point numbers can cause incorrect monetary values.

*/
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.
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值