我试图在
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);
- }
- }