我想要的是一种将双精度转换为字符串的方法,该字符串使用半向上舍入方法进行舍入-即,如果要舍入的小数为5,则始终向上舍入到下一个数字。这是大多数人在大多数情况下所期望的四舍五入的标准方法。

我还希望只显示有效数字,即不应有任何尾随零。

我知道这样做的一种方法是使用String.format方法:

String.format("%.5g%n", 0.912385);

返回:

0.91239

这是很好的,但是它总是显示带有5位小数的数字,即使它们不重要:

String.format("%.5g%n", 0.912300);

返回:

0.91230

另一种方法是使用DecimalFormatter:

DecimalFormat df = new DecimalFormat("#.#####");
df.format(0.912385);

返回:

0.91238

然而,正如您所见,这使用了半偶数舍入。也就是说,如果前一个数字是偶数,它将向下舍入。我想要的是:

0.912385 -> 0.91239
0.912300 -> 0.9123

在Java中实现这一点的最佳方法是什么?


当前回答

如果您希望结果为字符串,可以使用以下内容:

DecimalFormat#setRoundingMode():DecimalFormat df=新的DecimalFormat(“#.#####”);df.setRoundingMode(RoundingMode.HALF_UP);字符串str1=df.format(0.912385));//0.91239BigDecimal#setScale()字符串str2=新BigDecimal(0.912385).setScale(5,BigDecimal.ROUND_HALF_UP).toString();

这里有一个建议,如果你想要加倍,你可以使用哪些库。不过,我不建议将其用于字符串转换,因为double可能无法准确表示您想要的内容(请参见此处的示例):

Apache Commons数学中的精度双舍入=精度舍入(0.912385,5,BigDecimal.round_HALF_UP);Colt函数双舍入=函数。舍入(0.00001)。应用(0.912385)来自Weka的Utilsdoubleround=Utils.roundDouble(0.912385,5)

其他回答

以防有人仍需要帮助。这个解决方案非常适合我。

private String withNoTrailingZeros(final double value, final int nrOfDecimals) {
return new BigDecimal(String.valueOf(value)).setScale(nrOfDecimals,  BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();

}

返回具有所需输出的字符串。

double myNum = .912385;
int precision = 10000; //keep 4 digits
myNum= Math.floor(myNum * precision +.5)/precision;

我的答案是:

double num = 4.898979485566356;
DecimalFormat df = new DecimalFormat("#.##");      
time = Double.valueOf(df.format(num));

System.out.println(num); // 4.89

如果需要加倍,可以使用以下方法

double getRandom(int decimalPoints) {
    double a = Math.random();
    int multiplier = (int) Math.pow(10, decimalPoints);
    int b = (int) (a * multiplier);
    return b / (double) multiplier;
}

例如getRandom(2)

为了使后面的0一直到第5位

DecimalFormat decimalFormatter=新的DecimalFormat(“#.000000”);decimalFormatter.format(0.350500);//结果0.350500

为了避免0拖到第5位

DecimalFormat decimalFormatter=新的DecimalFormat(“#.#####”);decimalFormatter.format(0.350500);//结果o.3505