本文介绍了Java:使用DecimalFormat格式化双精度和整数,但保留不带小数分隔符的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在Java程序中格式化一些数字。数字将是双重和整数。处理双精度时,我只想保留两个小数点,但是当处理整数时,我希望程序保持不变。换句话说:双打 - 输入
14.0184849945
双打 - 输出
14.01
整数 - 输入
13
整数 - 输出
13(不是13.00)
有没有办法在相同的 DecimalFormat实例中实现?到目前为止,我的代码如下:
DecimalFormat df = new DecimalFormat(#,###,## 0.00 );
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
otherSymbols.setDecimalSeparator('。');
otherSymbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(otherSymbols);
解决方案
您可以设置 minimumFractionDigits
to 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);
}
}
I'm trying to format some numbers in a Java program. The numbers will be both doubles and integers. When handling doubles, I want to keep only two decimal points but when handling integers I want the program to keep them unaffected. In other words:
Doubles - Input
14.0184849945
Doubles - Output
14.01
Integers - Input
13
Integers - Output
13 (not 13.00)
Is there a way to implement this in the same DecimalFormat instance? My code is the following, so far:
DecimalFormat df = new DecimalFormat("#,###,##0.00");
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
otherSymbols.setDecimalSeparator('.');
otherSymbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(otherSymbols);
解决方案
You can just set the minimumFractionDigits
to 0. Like this:
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);
}
}
这篇关于Java:使用DecimalFormat格式化双精度和整数,但保留不带小数分隔符的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!