Java 如何使用十进制格式使 0 显示为 0.00?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26706784/
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
How to make 0 display as 0.00 using decimal format?
提问by Hiten Naresh Vasnani
I am using the following code to make numbers display with two decimal places and thousands comma separator.
我正在使用以下代码使数字显示为两位小数和千位逗号分隔符。
public static String formatNumber(double amount){
DecimalFormat formatter = new DecimalFormat("#,###.00");
return formatter.format(amount);
}
For other numbers it is ok but 0 is returned as ".00" I want it to be "0.00" What should I change?
对于其他数字,它可以,但 0 返回为“.00” 我希望它是“0.00” 我应该改变什么?
采纳答案by JClassic
Why not
为什么不
return String.format("%.2f", amount);
That would format it correctly wouldn't it? (if amount is 123123.14233 then it would return 123123.14)
那会正确格式化它不是吗?(如果金额是 123123.14233 那么它将返回 123123.14)
or
或者
return String.format("%,.2f", amount);
for commas within the number. (if amount is 123123.14233 then it would return 123,123.14)
对于数字中的逗号。(如果金额是 123123.14233 那么它将返回 123,123.14)
回答by eckes
The #
means optional digit, so if you use 0
instead it will work:
这#
意味着可选数字,所以如果你使用0
它会起作用:
DecimalFormat formatter = new DecimalFormat("#,##0.00");
BTW: I think you need 3 ###
not 4.
BTW:我认为你需要 3 个###
而不是 4 个。