Reputation: 5
I am trying to format double values, so it they would have only 2 decimal spaces:
remainingAmount = Double.parseDouble(String.format("%.2f",remainingAmount - calculatePrincipalPayment()));
As you can see, this code formats double value remainingAmount - calculatePrincipalPayment()
using String.format()
, then transfers it from String to Double and assigns it to the double variable remainingAmount (which was declared). remainingAmount
is double and calculatePrincipalPayment()
returns double.
The problem is that it formats only part of the values, for example it can return 401.37 (which is the required formatting) as well as 403.71999999999997. I also already tried to do formatting by using DecimalFormat df = new DecimalFormat("#.##").
Upvotes: 0
Views: 1239
Reputation: 425033
A double
(or its boxed counterpart Double
) has no capacity to store a specific format to be used when rendering as a String. It is just a raw value.
I suspect you believe that a double
value obtained by parsing from a specific format somehow retains that format. This is not the case.
Floating point types are imprecise; not all values can be accurately stored. In cases where the exact value cannot be stored, the closest storable value is used - as is the case with some of your results.
Upvotes: 0