Thursday, September 18, 2014

EJ-48 Avoid Float And Double If Exact Answers are Required

Ref: Effective Java by Joshua Bloch

The float and double types are designed primarily for scientifc and engineering calculations. They perform binary floating point arithmetic. The float and double types are particularly illsuited for monetary calculations. Following unit test illustrates the problem and the right way to solve this problem by using BigDecimal.

In summary, don't use float or double for any calculations that require an exact answer. Use BigDecimal if you want the system to keep track of the decimalpoint and you don't mind the inconvenience and cost of not using a pritimitive type.

No comments: