Double decimal formatting in Java

Christoffer picture Christoffer · Oct 9, 2012 · Viewed 477.6k times · Source

I'm having some problems formatting the decimals of a double. If I have a double value, e.g. 4.0, how do I format the decimals so that it's 4.00 instead?

Answer

kosa picture kosa · Oct 9, 2012

One of the way would be using NumberFormat.

NumberFormat formatter = new DecimalFormat("#0.00");     
System.out.println(formatter.format(4.0));

Output:

4.00