[英]Java Double Format to show 2 decimal points even when zero
I want to print out double values onto the screen with 2 decimal points. 我想在屏幕上用2个小数点打印出双精度值。 So far this line has worked perfectly: 到目前为止,这条线已经完美运行:
System.out.println(new DecimalFormat("$#,###.##").format(value));
For inputs like: 对于像这样的输入:
double value = 82348238482834.23482348;
It prints out: 它输出:
$82,348,238,482,834.23
Which is exactly what I want. 这正是我想要的。 However, if I have the input 0
I want it to print out $0.00
. 但是,如果我有输入0
我希望它打印出$0.00
。 With the above format line it prints out $0
. 使用上述格式行,它将输出$0
。 I tried changing the above code to: 我尝试将上面的代码更改为:
double value = 0;
System.out.println(new DecimalFormat("$#,###.00").format(value));
But that printed out $.00
. 但这打印了$.00
。 I could just do this: 我可以这样做:
if(value == 0) {
System.out.println("$0.00");
}
It works but it's very ugly. 它可以工作,但是非常难看。 Is there any other way to solve this issue? 还有其他解决方法吗?
Use: 采用:
System.out.println(new DecimalFormat("$#,##0.00").format(value));
Changed: 已更改:
"$#,##0.00"
Like Jon said, 0 indicates a digit so it includes zero, # indicates a digit but zero shows as absent. 如Jon所说,0表示一个数字,因此它包括零,#表示一个数字,但零表示不存在。
For more info on DecimalFormat. 有关DecimalFormat的更多信息。
I do not understand why people still use this DecimalFormat
stuff. 我不明白为什么人们仍然使用DecimalFormat
东西。 To achieve what you want just use System.out.printf
with the following pattern. 要实现所需的功能,只需将System.out.printf
与以下模式一起使用。
System.out.printf("%,.2f%n", value);
If the value is 0
it will be always printed as 0.00
or 0,00
depending on locale. 如果值为0
,则根据区域设置,它将始终打印为0.00
或0,00
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.