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.

 

你可能感兴趣的:(BigDecimal,double,float,round)