17

I'm trying to format some numbers in a Java program. The numbers will be both doubles and integers. When handling doubles, I want to keep only two decimal points but when handling integers I want the program to keep them unaffected. In other words:

Doubles - Input

14.0184849945

Doubles - Output

14.01

Integers - Input

13

Integers - Output

13 (not 13.00)

Is there a way to implement this in the same DecimalFormat instance? My code is the following, so far:

DecimalFormat df = new DecimalFormat("#,###,##0.00");
DecimalFormatSymbols otherSymbols = new   DecimalFormatSymbols(Locale.ENGLISH);
otherSymbols.setDecimalSeparator('.');
otherSymbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(otherSymbols);
Lefteris008
  • 899
  • 3
  • 10
  • 29
  • 4
    Why does it have to be the same `DecimalFormat` instance? What's wrong with having 2 `DecimalFormat` instances, one to keep two digits past the decimal point, and one not to have any digits past the decimal point? – rgettman Apr 30 '13 at 21:29
  • Because the numbers which the program formats every time are either doubles or integers, without knowing the type before the formation. So, I want the same instance which will "understand" whether a number is double -to trim extra decimal points- or it is an integer -to keep it unaffected. – Lefteris008 May 01 '13 at 09:50

2 Answers2

29

You can just set the minimumFractionDigits to 0. Like this:

public class Test {

    public static void main(String[] args) {
        System.out.println(format(14.0184849945)); // prints '14.01'
        System.out.println(format(13)); // prints '13'
        System.out.println(format(3.5)); // prints '3.5'
        System.out.println(format(3.138136)); // prints '3.13'
    }

    public static String format(Number n) {
        NumberFormat format = DecimalFormat.getInstance();
        format.setRoundingMode(RoundingMode.FLOOR);
        format.setMinimumFractionDigits(0);
        format.setMaximumFractionDigits(2);
        return format.format(n);
    }

}
Rodrigo Sasaki
  • 7,048
  • 4
  • 34
  • 49
4

Could you not just wrapper this into a Utility call. For example

public class MyFormatter {

  private static DecimalFormat df;
  static {
    df = new DecimalFormat("#,###,##0.00");
    DecimalFormatSymbols otherSymbols = new   DecimalFormatSymbols(Locale.ENGLISH);
    otherSymbols.setDecimalSeparator('.');
    otherSymbols.setGroupingSeparator(',');
    df.setDecimalFormatSymbols(otherSymbols);
  }

  public static <T extends Number> String format(T number) {
     if (Integer.isAssignableFrom(number.getClass())
       return number.toString();

     return df.format(number);
  }
}

You can then just do things like: MyFormatter.format(int) etc.

zzlalani
  • 22,960
  • 16
  • 44
  • 73
Jeremy Unruh
  • 649
  • 5
  • 10
  • Just a small note: The type parameter on the `format` method don't actually do anything. Just remove it and use the `Number` type for the `number` parameter. – Lii May 02 '18 at 09:58