/*
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.
*/
Type float or double to perform monetary calculations
最新推荐文章于 2025-08-07 08:50:17 发布