I am trying to keep two decimal places, even if then numbers are zeroes, using DecimalFormatter
:
DecimalFormat df = new DecimalFormat("#.00");
m_interest = Double.valueOf(df.format(m_principal * m_interestRate));
m_newBalance = Double.valueOf(df.format(m_principal + m_interest - m_payment));
m_principal = Double.valueOf(df.format(m_newBalance));
However for some values this gives two decimal places, and for others it doesnt. How can i fix this?
It is because you are using
Double.valueOf
on theDecimalFormat
and it is converting the formatted number back to a double, therefore eliminating the trailing 0s.To fix this, only use the
DecimalFormat
when you are displaying the value.If you need
m_interest
calculations, keep it as a regulardouble
.Then when displaying, use:
Example:
DecimalFormat and NumberFormat should work just fine. A currency instance could work even better:
This would output:
Use BigDecimal instead, which supports the formatting approach you seek.
This question details it: How to print formatted BigDecimal values?
Why don't you simply Math.round(value * 100) / 100.0 ?