gpt4 book ai didi

Java使用bigdecimal计算被3整除到百

转载 作者:行者123 更新时间:2023-12-01 09:07:47 25 4
gpt4 key购买 nike

这是我计算金额百分比的示例代码,在给定的示例中,我预计返回为 10,但它给了我 9.9。我如何将其四舍五入到 10?

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;


public class Test {


public static final int AMOUNT_SCALE = 2;
public static final int PRECISION_SIX = 6;
private static BigDecimal tmp = new BigDecimal("100");
public static final BigDecimal ONE_HUNDRED = tmp.setScale(0, RoundingMode.DOWN);
public static final MathContext MATH_CONTEXT = new MathContext(PRECISION_SIX, RoundingMode.HALF_UP);

public static void main(String [] args){
System.out.println(multiplyTwoNumbersAndDivideByOneHundredAmount(new BigDecimal(30), new BigDecimal(33.33))); ;
}

public static BigDecimal multiplyTwoNumbersAndDivideByOneHundredAmount(BigDecimal firstNumber, BigDecimal secondNumber) {
return (firstNumber.multiply(secondNumber)).divide(ONE_HUNDRED,MATH_CONTEXT).setScale(AMOUNT_SCALE,RoundingMode.DOWN);
}
}

最佳答案

.setScale(0, RoundingMode.HALF_UP);

这就是您要找的。

关于Java使用bigdecimal计算被3整除到百,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41124008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com