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?
1. DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places.
To be able to print any given number with two zeros after the decimal point, we'll use one more time DecimalFormat class with a predefined pattern: public static double withTwoDecimalPlaces(double value) { DecimalFormat df = new DecimalFormat("#. 00"); return new Double(df.
Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.
Call str. format(*args) with "{:. 2f}" as str and a float as *args to limit the float to two decimal places as a string.
It is because you are using Double.valueOf
on the DecimalFormat
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 regular double
.
Then when displaying, use:
System.out.print(df.format(m_interest));
Example:
DecimalFormat df = new DecimalFormat("#.00");
double m_interest = 1000;
System.out.print(df.format(m_interest)); // prints 1000.00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With