When we calculate 1.00 - 0.90, the answer is not 0.1 but 0.09999999999999998.
The float and double types are primarily designed for scientific calculations. If we want to get exact answer, we can use int, long or BigDecimal.
Like:
BigDecimal a = new BigDecimal("1.00");
BigDecimal b = new BigDecimal("0.90");
BigDecimal c = a.subtract(b);
It's less convenient than using a primitive arithmetic type. An alternative choice is to use int or long.
Reference:
<Effective Java> Chapert 7
No comments:
Post a Comment