简体   繁体   English

Java:BigDecimal 向上取整百万

[英]Java: BigDecimal round up for million number

I have a method that calculates 17780.00 x 115.00, the result should be 2044700.00, however, the method calculated it as 2045000.00 (seems to be rounded up for the whole number).我有一个计算 17780.00 x 115.00 的方法,结果应该是 2044700.00,但是,该方法将其计算为 2045000.00(似乎是四舍五入的整数)。 This method will also handle numbers with decimals, eg.此方法还将处理带小数的数字,例如。 0.97 x 0.5. 0.97 x 0.5。 The code looks like this:代码如下所示:

  public Double multiplyNumber(Double d1, Double d2) {

     return new BigDecimal(d1).multiply(
           new BigDecimal(d2), 
           new MathContext(4, RoundingMode.HALF_UP)).doubleValue(); 
  }

Please advise how to make the code calculate the correct result.请告知如何使代码计算出正确的结果。 Thanks!谢谢!

Rounding only deals with digits after the decimal place.四舍五入只处理小数点后的数字。 To round at places to the left, divide, round, multiply back:在左边的地方四舍五入,除法,四舍五入,乘以:

public Double multiplyNumber(Double d1, Double d2) {
    return new BigDecimal(d1)
            .multiply(new BigDecimal(d2))
            .divide(BigDecimal.TEN.pow(3), new MathContext(0, RoundingMode.HALF_UP))
            .multiply(BigDecimal.TEN.pow(3))
            .doubleValue();
}

BTW, this also produces the value you want:顺便说一句,这也会产生你想要的价值:

public Double multiplyNumber(Double d1, Double d2) {
    return d1 * d2;
}

You try run this.你试试运行这个。

public class Test {

    public static void main(String... strings)  {

        System.out.println("result "+multiplyNumber(17780.00, 115.00) );
    }

    public static Double multiplyNumber(Double d1, Double d2) {

         return new BigDecimal(d1).multiply(
               new BigDecimal(d2)).setScale(4, RoundingMode.HALF_UP).doubleValue(); 
    }
    
}

请改用以下 return 语句:

return new BigDecimal(d1).multiply(new BigDecimal(d2)).round(new MathContext(4, RoundingMode.HALF_UP)).doubleValue();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM