[英]Java: Use DecimalFormat to format doubles and integers but keep integers without a decimal separator
我正在尝试在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);
你可以将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);
}
}
你能不能把它包装成一个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)
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.