java 在以下情况下使用 DecimalFormat
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2213410/
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
Usage of DecimalFormat for the following case
提问by Cheok Yan Cheng
I have the following decimal format previously :
我以前有以下十进制格式:
private static final DecimalFormat decimalFormat = new DecimalFormat("0.00");
So,
所以,
it can change :
它可以改变:
0.1 -> "0.10"
0.01 -> "0.01"
0.001 -> "0.00"
What I wish is
我希望的是
0.1 -> "0.10"
0.01 -> "0.01"
0.001 -> "0.001"
Is it possible I can achieve so using DecimalFormat?
我有可能使用 DecimalFormat 来实现吗?
回答by Gladwin Burboz
DecimalFormat class is not "Thread Safe". So you are better off having static String variable for this format while you should define the DecimalFormat object within your method required method.
DecimalFormat 类不是“线程安全”。因此,您最好为此格式使用静态 String 变量,而您应该在方法所需的方法中定义 DecimalFormat 对象。
Static variable:
静态变量:
private static final String decimalFormatStr = "0.00#";
.
.
Local variable in method:
方法中的局部变量:
DecimalFormat decimalFormat = new DecimalFormat(decimalFormatStr);
回答by Mark Byers
Yes, use this:
是的,使用这个:
new DecimalFormat("0.00######");
The #means a digit should be displayed there except for trailing zeros. The 0means a digit is always displayed, even if it is a trailing zero. The number of decimal places in the formatted string will not exceed the total number of 0s and #s after the dot, so in this example the digits after the 8th decimal place will be truncated.
这#意味着除了尾随零之外,应该在那里显示一个数字。这0意味着总是显示一个数字,即使它是一个尾随零。格式化后的字符串中的小数位数不会超过点后的0s和#s的总数,因此本例中小数点后第8位的数字将被截断。
回答by Omar Al Kababji
You can do it like this:
你可以这样做:
NumberFormat f = NumberFormat.getNumberInstance();
f.setMinimumFractionDigits(2);
System.out.println(f.format(0.1));
System.out.println(f.format(0.01));
System.out.println(f.format(0.001));

