Java:使用 DecimalFormat 格式化双精度数和整数,但保留没有小数分隔符的整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16309189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Use DecimalFormat to format doubles and integers but keep integers without a decimal separator
提问by Lefteris008
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:
我正在尝试在 Java 程序中格式化一些数字。数字将是双精度数和整数。处理双精度数时,我只想保留两个小数点,但在处理整数时,我希望程序不影响它们。换句话说:
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 sameDecimalFormat instance? My code is the following, so far:
有没有办法在同一个DecimalFormat 实例中实现它?到目前为止,我的代码如下:
DecimalFormat df = new DecimalFormat("#,###,##0.00");
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
otherSymbols.setDecimalSeparator('.');
otherSymbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(otherSymbols);
采纳答案by Rodrigo Sasaki
You can just set the minimumFractionDigits
to 0. Like this:
您可以将 设置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);
}
}
回答by Jeremy Unruh
Could you not just wrapper this into a Utility call. For example
你能不能把它包装成一个实用程序调用。例如
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);
}
}
You can then just do things like: MyFormatter.format(int)
etc.
然后,您可以执行以下操作:MyFormatter.format(int)
等。