java BigDecimalDemo
No command-line arguments: enter two numbers eg 1.23 45.678:
39856398.767624534 0.00625
39856398.767625 + 0.006250 = 39856398.773875
39856398.767625 - 0.006250 = 39856398.761375
39856398.767625 × 0.006250 = 249102.492298
39856398.767625 ÷ 0.006250 = 6377023802.819925
39856398.767625 % 0.006250 = 0.005125
Note the %f tag defaults to 6 decimal places.
So far, so good. You can get 1 from 0.00625 if you repeatedly multiply by 2 or 5, so the division will eventually come out exactly. But what if the division isn't exact?
java BigDecimalDemo 9.0 0.7
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(BigDecimal.java:1616)
at BigDecimalDemo.ShowOperations(BigDecimalDemo.java:25)
at BigDecimalDemo.main(BigDecimalDemo.java:41)
We now need a version 2.
Apart from the imports, the change is on lines 27-28. You supply a rounding mode and a precision. In this case 4 appears to mean 4 significant figures, not four places after the decimal point. If you try to find the
divide() method, you find it is overloaded about 6 times to allow for that problem. Any overloading can be used, but they may give slightly different results.
Another thing is, BigDecimal is an immutable class. You will see the values of number1 and number2 do not change in the arithmetic.
Its equals() method includes the scale as well as the value, so 1.0 and 1.00 are not the same, but new BigDecimal("1.0").compareTo(new BigDecimal("1.000") will return 0, so you can use the compareTo method.
Don't use the constructor which takes a
double, but use one of the other constructors. You can see if you try System.out.println(new BigDecimal(1.23)); and with "1.23", and see the differences.
Read the BigDecimal and RoundingMode and MathContext documentation.