What I would like is a method to convert a double to a string which rounds using the half-up method - ie if the decimal to be rounded is 5, it always rounds up to the next number.
(我想要的是一种将双精度数转换为使用Half-up方法取整的字符串的方法-即,如果要取整的小数为5,则始终将其取整为下一个数字。)
This is the standard method of rounding most people expect in most situations. (这是大多数人在大多数情况下期望的四舍五入标准方法。)
I also would like only significant digits to be displayed - ie there should not be any trailing zeroes.
(我也希望只显示有效数字-即不应有任何尾随零。)
I know one method of doing this is to use the String.format
method:
(我知道这样做的一种方法是使用String.format
方法:)
String.format("%.5g%n", 0.912385);
returns:
(返回:)
0.91239
which is great, however it always displays numbers with 5 decimal places even if they are not significant:
(这很好,但是即使数字不重要,它也始终显示5位小数:)
String.format("%.5g%n", 0.912300);
returns:
(返回:)
0.91230
Another method is to use the DecimalFormatter
:
(另一种方法是使用DecimalFormatter
:)
DecimalFormat df = new DecimalFormat("#.#####");
df.format(0.912385);
returns:
(返回:)
0.91238
However as you can see this uses half-even rounding.
(但是,如您所见,这使用了半数舍入。)
That is it will round down if the previous digit is even. (如果前一位是偶数,它将四舍五入。)
What I'd like is this: (我想要的是这样的:)
0.912385 -> 0.91239
0.912300 -> 0.9123
What is the best way to achieve this in Java?
(用Java实现此目标的最佳方法是什么?)
ask by Alex Spurling translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…