IEEE 754 Floating Point Representation & BigDecimal
1Concept
Binary floating point types (float and double) follow the IEEE 754 binary floating-point standard. Because decimal numbers like 0.1 cannot be represented precisely in binary base-2, calculations like 0.1 + 0.2 yield 0.30000000000000004. Financial and accounting software must use java.math.BigDecimal with String constructors.
2Architecture Diagram
Double Binary Storage: 0.1 + 0.2 ---> 0.30000000000000004 (Imprecise!)
BigDecimal Storage: new BigDecimal("0.1").add(new BigDecimal("0.2")) ---> 0.3 (Exact Precision!)3Code Example
Core Java
import java.math.BigDecimal;
import java.math.RoundingMode;
public class PreciseMonetaryDemo {
public static void main(String[] args) {
double d1 = 0.1;
double d2 = 0.2;
System.out.println("double 0.1 + 0.2: " + (d1 + d2));
BigDecimal b1 = new BigDecimal("0.1");
BigDecimal b2 = new BigDecimal("0.2");
BigDecimal sum = b1.add(b2);
System.out.println("BigDecimal '0.1' + '0.2': " + sum);
BigDecimal num = new BigDecimal("10");
BigDecimal den = new BigDecimal("3");
BigDecimal result = num.divide(den, 4, RoundingMode.HALF_UP);
System.out.println("10 / 3 (4 decimals): " + result);
}
}4Expected Output
double 0.1 + 0.2: 0.30000000000000004 BigDecimal '0.1' + '0.2': 0.3 10 / 3 (4 decimals): 3.3333
5Key Takeaways
- ✓NEVER use double or float for currency or financial calculations.
- ✓ALWAYS construct BigDecimal using String constructors: new BigDecimal("0.1"), NOT new BigDecimal(0.1).
- ✓Division with BigDecimal requires explicit RoundingMode to prevent ArithmeticException on non-terminating decimals.