
问题
我正在尝试在Java程序中格式化一些数字. 数字将是双精度和整数. 当处理双精度数时,我只想保留两个小数点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);
}
}
本文地址: IT之家»Java: 使用DecimalFormat格式化双精度和整数,但保留不带小数分隔符的整数
问题
我正在尝试在Java程序中格式化一些数字. 数字将是双精度和整数. 在处理双精度时,我只想保留两个小数点,但是在处理整数时,我希望程序保持不变. 换句话说:

Doubles-Enter
14.0184849945
双打输出
14.01
整数输入
13

整数输出
13(不是13.00)
是否可以在同一DecimalFormat实例中实现它?到目前为止java格式化小数,我的代码如下:
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)); //打印'13'
System.out.println(format(3.5)); //打印'3.5'
System.out.println(format(3.138136)); // print'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);
}
}
本文地址: IT之家»Java: 使用DecimalFormat格式化双精度和整数,但保留不带小数分隔符的整数
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-160654-1.html
今年30一公斤
尤其改革开放初期
越来越优秀