`
leonzhx
  • 浏览: 793781 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 48: Avoid float and double if exact answers are required

阅读更多

1.  The float and double types are particularly illsuited for monetary calculations because it is impossible to represent 0.1 (or any other negative power of ten) as a float or double exactly. The right way to solve this problem is to use BigDecimal, int, or long for monetary calculations.

 

2.  Using BigDecimal has the added advantage that it gives you full control over rounding, letting you select from eight rounding modes whenever an operation that entails rounding is performed. This comes in handy if you’re performing business calculations with legally mandated rounding behavior.

 

3.  There are, however, two disadvantages to using BigDecimal: it’s less convenient than using a primitive arithmetic type, and it’s slower. An alternative to using BigDecimal is to use int or long, depending on the amounts involved, and to keep track of the decimal point yourself.

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics