`
ShorenG
  • 浏览: 5142 次
  • 性别: Icon_minigender_1
  • 来自: 火星
最近访客 更多访客>>
社区版块
存档分类
最新评论

Type float or double to perform monetary calculations

    博客分类:
  • Java
 
阅读更多
 /*

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.
*/
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics