如何在Java中将double舍入到两位小数?

72

这是我用来将一个双精度数舍入到小数点后2位的方法:

amount = roundTwoDecimals(amount);

public double roundTwoDecimals(double d) {
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(twoDForm.format(d));
}

如果amount=25.3569或类似于此的数,这个方法非常好用。但是如果amount=25.00或amount=25.0,那么结果会是25.0!我想做到同时四舍五入并格式化为2位小数。


这个函数在安卓上有时会返回逗号而不是点,因此 Double.valueOf() 会抛出异常。 - max4ever
21个回答

1

从Java 1.8开始,您可以使用Lambda表达式和空值检查来实现更多功能。此外,下面的代码可以处理Float或Double以及可变数量的小数点(包括2个:-)。

public static Double round(Number src, int decimalPlaces) {

    return Optional.ofNullable(src)
            .map(Number::doubleValue)
            .map(BigDecimal::new)
            .map(dbl -> dbl.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP))
            .map(BigDecimal::doubleValue)
            .orElse(null);
}

1
DecimalFormat df = new DecimalFormat("###.##");
double total = Double.valueOf(val);

一旦超过999,这个解决方案与原始代码存在相同的问题。 - artdanil

1
你的 Money 类可以表示为 Long 类的子类,或者具有表示原生长整型货币值的成员。这样,当将值分配给你的 Money 实例时,你将始终存储实际的真正货币值。你只需通过适当的格式输出 Money 对象(通过 Money 的重载 toString() 方法),例如 $1.25 在 Money 对象的内部表示中为 125。你将钱表示为分、便士或任何你正在处理的货币的最小面值……然后在输出时进行格式化。现在你永远不可能存储“非法”的货币值,比如说 $1.257。

1

你可以尝试这个:

public static String getRoundedValue(Double value, String format) {
    DecimalFormat df;
    if(format == null)
        df = new DecimalFormat("#.00");
    else 
        df = new DecimalFormat(format);
    return df.format(value);
}

或者

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

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
}

0

如果你想要结果保留两位小数,可以这样做

// assuming you want to round to Infinity.
double tip = (long) (amount * percent + 0.5) / 100.0; 

这个结果不是很精确,但 Double.toString(double) 可以纠正这个问题并打印一到两位小数。然而,一旦您执行另一个计算,您可能会得到一个不会被隐式舍入的结果。 ;)


0

Math.round 是一个答案,

public class Util {
 public static Double formatDouble(Double valueToFormat) {
    long rounded = Math.round(valueToFormat*100);
    return rounded/100.0;
 }
}

在 Spock、Groovy 中进行测试

void "test double format"(){
    given:
         Double performance = 0.6666666666666666
    when:
        Double formattedPerformance = Util.formatDouble(performance)
        println "######################## formatted ######################### => ${formattedPerformance}"
    then:
        0.67 == formattedPerformance

}

使用valueToFormat = 0d时,返回0.0而不是0.00。原始问题询问小数位为0时是否仍保留两个小数位。 - Atul Kumbhar

0

假设数量既可以是正数也可以是负数,将其四舍五入到小数点后两位,可以使用以下代码片段。

amount = roundTwoDecimals(amount);

public double roundTwoDecimals(double d) {
    if (d < 0)
       d -= 0.005;
    else if (d > 0)
       d += 0.005;
    return (double)((long)(d * 100.0))/100);
}

0

其中num是双精度数字

  • 整数2表示我们想要打印的小数位数。
  • 这里我们取2位小数

    System.out.printf("%.2f",num);


0
    int i = 180;
    int j = 1;
    double div=  ((double)(j*100)/i);
    DecimalFormat df = new DecimalFormat("#.00"); // simple way to format till any deciaml points
    System.out.println(div);
    System.out.println(df.format(div));

0

这里有一个简单的方法,保证输出myFixedNumber保留两位小数:

import java.text.DecimalFormat;

public class TwoDecimalPlaces {
    static double myFixedNumber = 98765.4321;
    public static void main(String[] args) {

        System.out.println(new DecimalFormat("0.00").format(myFixedNumber));
    }
}

结果是:98765.43


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