本文翻译自:Best way to Format a Double value to 2 Decimal places [duplicate]
Possible Duplicate: 可能重复:
Round a double to 2 significant figures after decimal point 将小数点后的两位有效数字四舍五入
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? 我正在处理应用程序中的许多双精度值,是否有任何简单的方法来处理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 我基本上想做的是格式化double值,例如
23.59004 to 23.59
35.7 to 35.70
3.0 to 3.00
9 to 9.00
#1楼
参考:https://stackoom.com/question/B0rw/将Double值格式化为-个小数位的最佳方法-重复
#2楼
No, there is no better way. 不,没有更好的方法。
Actually you have an error in your pattern. 实际上,您的模式中有一个错误。 What you want is: 您想要的是:
DecimalFormat df = new DecimalFormat("#.00");
Note the "00"
, meaning exactly two decimal places. 注意"00"
, 恰好是两个小数位。
If you use "#.##"
( #
means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d);
如果使用"#.##"
( #
表示“可选”数字),它将删除尾随的零-即new DecimalFormat("#.##").format(3.0d);
prints just "3"
, not "3.00"
. 只打印"3"
而不是"3.00"
。
#3楼
An alternative is to use String.format
: 另一种方法是使用String.format
:
double[] arr = { 23.59004,
35.7,
3.0,
9
};
for ( double dub : arr ) {
System.out.println( String.format( "%.2f", dub ) );
}
output: 输出:
23.59
35.70
3.00
9.00
You could also use System.out.format
(same method signature), or create a java.util.Formatter
which works in the same way. 您也可以使用System.out.format
(相同的方法签名),或创建一个以相同方式工作的java.util.Formatter
。