我想要的是一种将双精度转换为字符串的方法,该字符串使用半向上舍入方法进行舍入-即,如果要舍入的小数为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中实现这一点的最佳方法是什么?


当前回答

我在java8中使用过类似于bellow的语言。它对我有用

    double amount = 1000.431;        
    NumberFormat formatter = new DecimalFormat("##.00");
    String output = formatter.format(amount);
    System.out.println("output = " + output);

输出:

output = 1000.43

其他回答

您可以使用以下实用程序方法-

public static double round(double valueToRound, int numberOfDecimalPlaces)
{
    double multipicationFactor = Math.pow(10, numberOfDecimalPlaces);
    double interestedInZeroDPs = valueToRound * multipicationFactor;
    return Math.round(interestedInZeroDPs) / multipicationFactor;
}

非常简单的方法

public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    DecimalFormat deciFormat = new DecimalFormat();
    deciFormat.setMaximumFractionDigits(places);
    String newValue = deciFormat.format(value);

    return Double.parseDouble(newValue);

}

double a = round(12.36545, 2);

简洁的解决方案:

   public static double round(double value, int precision) {
      int scale = (int) Math.pow(10, precision);
      return (double) (Math.round(value * scale) / scale);
  }

另请参见,https://stackoverflow.com/a/22186845/212950感谢jpdymond提供此服务。

编辑:添加圆括号。将整个结果强制加倍,而不仅仅是第一个参数!

这是我发现的只显示两位小数的最简单方法。

double x = 123.123;
System.out.printf( "%.2f", x );

为此,我们可以使用此格式化程序:

 DecimalFormat df = new DecimalFormat("#.00");
 String resultado = df.format(valor)

or:

DecimalFormat df = new DecimalFormat("0.00"); :

使用此方法始终获得两个小数:

   private static String getTwoDecimals(double value){
      DecimalFormat df = new DecimalFormat("0.00"); 
      return df.format(value);
    }

定义此值:

91.32
5.22
11.5
1.2
2.6

使用该方法,我们可以得到以下结果:

91.32
5.22
11.50
1.20
2.60

在线演示。