Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 688
Jon Avatar asked May 16 '13 09:05

Jon


People also ask

What is number format and DecimalFormat class?

DecimalFormat class is subclass of NumberFormat class and it is used to format numbers by using specify formatting pattern. We can format a number upto 2 decimal place,upto 3 decimal place, using comma to separate digits.

How do you display upto 2 decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.

What is decimal number format?

The "D" (or decimal) format specifier converts a number to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative. This format is supported only for integral types. The precision specifier indicates the minimum number of digits desired in the resulting string.


2 Answers

There is a slight difference between these two formats. The "#.##" means it will print the number with maximum two decimal places whereas "#.00" means it will always display two decimal places and if the decimal places are less than two, it will replace them with zeros. see the example below with output.

public static final DecimalFormat df1 = new DecimalFormat( "#.##" );
public static final DecimalFormat df2 = new DecimalFormat( "#.00" );

System.out.println(df1.format(7.80));
System.out.println(df1.format(85));
System.out.println(df1.format(85.786));

System.out.println(df2.format(7.80));
System.out.println(df2.format(85));
System.out.println(df2.format(85.786));

And the output will be

7.8
85
85.79

7.80
85.00
85.79
like image 195
Raza Avatar answered Sep 20 '22 12:09

Raza


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$", "");
}
like image 35
ntalbs Avatar answered Sep 19 '22 12:09

ntalbs