Asdfasf

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.

package first;
import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import org.junit.Test;
public class BigDecimalTest {
@Test
public void test() {
double result1 = new BigDecimal("1.00").subtract(new BigDecimal(".9")).doubleValue();
double result2 = 1.00 - .9; //Expecting 0.1 but NOT
System.out.println(result1);
System.out.println(result2);
assertEquals (0.1, result1, 0);
assertEquals(true, 0.1 == result1);
assertEquals(false, 0.1 == result2);
assertEquals(true, 0.09999999999999998 == result2);
}
}


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: