This is what I have so far,
And here is the output I get,
Why do I get the output after year 2? I assume it has something to do with the remainder.
I also have to format this output with the decimal point, etc.. which I think I will be ok with after I get through this part.
I am not sure what to recommend. You could try using long arithmetic, but that will eventually run out of space. The best way to calculate money is with the BigDecimal class.
After the book shows this program as an example, it goes on to say that this (using double) is not the best method for achieving accurate results, then it states "you've been warned!". It never gives a solution apart from a quick reference to the existence of BigDecimal but not how to use it.
Then I am given this problem, so that how I got here!
Thanks! I will go the BigDecimal route!
Note the %f tag defaults to 6 decimal places.
No command-line arguments: enter two numbers eg 1.23 45.678:
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
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?
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.
java BigDecimalDemo 9.0 0.7
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
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.
Thank you again!
So, try this:. . . as an alternative to line 27 above. That seems to give 4 places after the decimal point.
Last year, I wrote: . . . the divide() method . . . is overloaded about 6 times to allow for that problem. Any overloading can be used, but they may give slightly different results. . . .