将 Double 值格式化为 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?
有没有比
DecimalFormat df = new DecimalFormat("#.##");
我想要做的基本上是像
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.
如果您使用 "#.##"
(#
表示可选"数字),它将删除尾随零 - 即 new 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"
.