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

Java:使用DecimalFormat格式化双精度和整数,但保留整数时不使用小数分隔符,java,integer,double,decimalformat,Java,Integer,Double,Decimalformat,我试图在Java程序中格式化一些数字。这些数字将是双精度和整数。处理double时,我只希望保留两个小数点,但处理整数时,我希望程序不影响它们。换言之: 双工输入 14.0184849945 双倍输出 14.01 13 (not 13.00) 整数-输入 13 整数-输出 14.01 13 (not 13.00) 有没有办法在相同的DecimalFormat实例中实现这一点?到目前为止,我的代码如下: DecimalFormat df = new DecimalFormat("#,#

我试图在Java程序中格式化一些数字。这些数字将是双精度和整数。处理double时,我只希望保留两个小数点,但处理整数时,我希望程序不影响它们。换言之:

双工输入

14.0184849945
双倍输出

14.01
13 (not 13.00)
整数-输入

13
整数-输出

14.01
13 (not 13.00)
有没有办法在相同的DecimalFormat实例中实现这一点?到目前为止,我的代码如下:

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

你能不能把它包装成一个实用程序调用。比如说

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{
专用静态分集格式df;
静止的{
df=新的十进制格式(“0.00”);
DecimalFormatSymbols otherSymbols=新的DecimalFormatSymbols(Locale.ENGLISH);
其他符号。设置小数分隔符('.');
setGroupingSeparator(',');
df.setDecimalFormatSymbols(其他符号);
}
公共静态字符串格式(T编号){
if(Integer.isAssignableFrom(number.getClass())
返回编号.toString();
返回df.格式(编号);
}
}

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

您可以将
最小分数位数设置为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);
    }

}

为什么它必须是相同的
DecimalFormat
实例?有两个
DecimalFormat
实例有什么不对,一个保持两位数超过小数点,一个不超过小数点?因为程序每次格式化的数字要么是双精度的,要么是整数,而不知道类型在形成之前。所以,我想要相同的实例,它将“理解”一个数字是双精度的(用于修剪额外的小数点)还是一个整数(用于保持其不受影响)。现在它的格式为44.0到44,55.60到55.6。如何使用format保持结尾处的零?请注意:
format
方法上的type参数实际上没有任何作用。只需删除它并使用
number
type for
编号
参数。