将Double值格式化为2个小数位的最佳方法
可能重复:
小数点后的双倍到2位有效数字
我在应用程序中处理了很多双值,是否有简单的方法来处理Java中十进制值的格式?
I am dealing with lot of double values in my application, is there is any easy way to handle the formatting of decimal values in Java?
还有其他更好的方法吗?
Is there any other better way of doing it than
DecimalFormat df = new DecimalFormat("#.##");
我想要做的基本上是格式双值,如
What i want to do basically is format double values like
23.59004 to 23.59
35.7 to 35.70
3.0 to 3.00
9 to 9.00
不,没有更好的办法。
实际上你的模式有错误。你想要的是:
Actually you have an error in your pattern. What you want is:
DecimalFormat df = new DecimalFormat("#.00");
注意00
,意思是完全两位小数。
Note the "00"
, meaning exactly two decimal places.
如果你使用#。##
(#
表示可选数字),它将删除尾随零 - 即新的DecimalFormat(#。##)。format(3.0d);
只打印3
,而不是3.00
。
If you use "#.##"
(#
means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d);
prints just "3"
, not "3.00"
.