四舍五入到 4 位小数或更少

Round a double to 4 decimals or less

我目前使用的方法是:

String.format("%.4", myDouble);

这样做的问题是,如果我得到一个小数位数较少的数字,例如 2.34,它将显示 2.3400 。有没有办法避免这种情况?

您可以使用 Math.round 函数 :) 示例:

Math.round(192.15515452*10000)/10000.0

returns 192.1551

Math.round(192.15*10000)/10000.0

returns 192.15

使用 DecimalFormat 和模式 #.#### 应该可以。它会显示小数点后最多 4 位数字,但如果不需要,可能会更少。

http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

使用DecimalFormat和一个模式。

double value = 2.34;
String pattern = "#.####";
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);

System.out.println(value + " " + pattern + " " + output);  // displays  2.34 #.#### 2.34

更多参考资料Customizing Formats