Formatting numbers using DecimalFormat
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$", "");
}
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