Mistake #1: Using floating point data types like float or double for monetary calculations. This can lead to rounding issues.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.monetary; import java.math.BigDecimal; public class MonetaryCalc { public static void main(String[] args) { System.out.println(1.05 - 0.42); //1: $0.6300000000000001 //2: $0.63 System.out.println(new BigDecimal("1.05") .subtract(new BigDecimal("0.42"))); //3: $0.630000000000000059952043329758453182876110076904296875 System.out.println(new BigDecimal(1.05) .subtract(new BigDecimal(0.42))); //4: $0.63 System.out.println(BigDecimal.valueOf(1.05) .subtract(BigDecimal.valueOf(0.42))); System.out.println(105 - 42); //5: 63 cents } } |
In the above code, 2, 4, and 5 are correct and 1 and 3 are incorrect usage leading to…