Display a Double with two decimal places in Java

I just spent the longest time trying to find the easiest way to make a double display two decimal places in Java.

Basically, I wanted to output money information, and it would look better if the money data says “$5.00” instead of “$5.0” as is sometimes the case. There are so many “solutions” to this, that it is difficult to wade through them all.
The best solution I encountered was relatively easy. You can find it in Sun’s Java forums.

import java.text.DecimalFormat;

double d = 8.9909879;

DecimalFormat dFormat = new DecimalFormat(“0.00”);

String formattedString = dFormat.format(d));

The above code will format a string that has two decimal point precision. It will give the number 8.99 instead of 8.9909879.

2 thoughts on “Display a Double with two decimal places in Java

Leave a Reply