将双精度浮点数保留四位小数或更少

3
我目前正在使用的方法是:

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

问题在于,如果我得到一个小数点后面位数较少的数字,比如2.34,它将显示为2.3400。有没有办法避免这种情况?


2
使用 DecimalFormat 格式化十进制数... - Codebender
如果你在谈论百分比或者在科学领域使用这个数字,那么把它们都写成相同小数位数可能更清晰。例如,如果确切的数字是2.3400%,而下一个数字是5.8794%,那么前者应该写成2.3400。在这里,零是有意义的。 - rajah9
1
https://dev59.com/eGgt5IYBdhLWcg3w8h01 - Reimeus
3个回答

4

2
你可以使用 Math.round 函数 :) 例如:
Math.round(192.15515452*10000)/10000.0

返回 192.1551

Math.round(192.15*10000)/10000.0

返回 192.15


1
使用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

更多参考资料请查看 自定义格式

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接