Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - always keep two decimal places even in zeroes

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?

like image 860
user3044874 Avatar asked Dec 09 '13 04:12

user3044874


People also ask

How do I restrict to 2 decimal places in Java?

1. DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places.

How do I keep last 0s after decimal point for double data type in Java?

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.

How do you keep 2 decimal places?

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.

How do I restrict float to 2 decimal places?

Call str. format(*args) with "{:. 2f}" as str and a float as *args to limit the float to two decimal places as a string.


1 Answers

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
like image 100
Michael Yaworski Avatar answered Sep 17 '22 11:09

Michael Yaworski