简体   繁体   English

Java:使用DecimalFormat格式化双精度和整数,但保持整数不带小数分隔符

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

I'm trying to format some numbers in a Java program. 我正在尝试在Java程序中格式化一些数字。 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? 有没有办法在同一个 DecimalFormat实例中实现它? 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);

You can just set the minimumFractionDigits to 0. Like this: 你可以将minimumFractionDigits设置为0.像这样:

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);
    }

}

Could you not just wrapper this into a Utility call. 你能不能把它包装成一个Utility调用。 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. 然后,您可以执行以下操作: MyFormatter.format(int)等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM