Java: Use DecimalFormat to format doubles and integers but keep integers without a decimal separator

前端 未结 2 924
孤城傲影
孤城傲影 2020-12-17 10:23

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 h

2条回答
  •  清歌不尽
    2020-12-17 11:21

    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  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.

提交回复
热议问题