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

时间:2013-04-30 21:23:39

标签: java integer double decimalformat

我正在尝试在Java程序中格式化一些数字。数字将是双精度数和整数数。处理双精度时,我想只保留两个小数点,但在处理整数时,我希望程序保持不受影响。换句话说:

双打 - 输入

14.0184849945

双打 - 输出

14.01

整数 - 输入

13

整数 - 输出

13 (not 13.00)

有没有办法在相同的 DecimalFormat实例中实现它?到目前为止,我的代码如下:

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

2 个答案:

答案 0 :(得分:28)

您可以将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);
    }

}

答案 1 :(得分:3)

你能不能将它包装到Utility调用中。例如

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

然后您可以执行以下操作:MyFormatter.format(int)等。