如何在Java中将数字舍入到n个小数位 [英] How to round a number to n decimal places in Java
问题描述
我想要的是一种将double转换为使用half-up方法进行舍入的字符串的方法 - 即如果要舍入的小数是5,则它总是向上舍入到前一个数字。这是在大多数情况下舍入大多数人所期望的标准方法。
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the previous number. This is the standard method of rounding most people expect in most situations.
我还希望只显示有效数字 - 即不应该有任何尾随零。
I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes.
我知道这样做的一种方法是使用 String.format
方法:
I know one method of doing this is to use the String.format
method:
String.format("%.5g%n", 0.912385);
返回:
0.91239
这很好,但它始终显示5位小数的数字,即使它们并不重要:
which is great, however it always displays numbers with 5 decimal places even if they are not significant:
String.format("%.5g%n", 0.912300);
返回:
0.91230
另一种方法是使用 DecimalFormatter
:
DecimalFormat df = new DecimalFormat("#.#####");
df.format(0.912385);
返回:
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
用Java实现这一目标的最佳方法是什么?
What is the best way to achieve this in Java?
推荐答案
使用 setRoundingMode
,设置 RoundingMode
明确处理你的半圆形问题,然后使用所需输出的格式模式。
Use setRoundingMode
, set the RoundingMode
explicitly to handle your issue with the half-even round, then use the format pattern for your required output.
示例:
DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.CEILING);
for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {
Double d = n.doubleValue();
System.out.println(df.format(d));
}
给出输出:
12
123.1235
0.23
0.1
2341234.2125
这篇关于如何在Java中将数字舍入到n个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!