Search code examples
javadecimalformat

Formatting numbers using DecimalFormat


I am trying to format prices using DecimalFormat, but this isn't working for all variations.

DecimalFormat df = new DecimalFormat("0.##")
df.format(7.8)
df.format(85.0)

prints

7.80

and

85

but "7.79999" gets formatted as "7.8", not "7.80". I have tried doing things this way

DecimalFormat df = new DecimalFormat("0.00")

to force two dp, but then "85.0" gets formatted as "85.00" not "85"!

Is there a way of capturing all variations, so that prices are printed either as #, ##, or #.##? For example:

5, 55, 5.55, 5.50, 500, 500.40


Solution

  • This doesn't seem to be solved by a single formatter. I suggest you use "0.00" format and replace ".00" with an empty string.

    public static String myFormat(double number) {
      DecimalFormat df = new DecimalFormat("0.00");
      return df.format(number).replaceAll("\\.00$", "");
    }