gpt4 book ai didi

groovy - groovy中bigdecimal的默认比例

转载 作者:行者123 更新时间:2023-12-02 18:13:51 25 4
gpt4 key购买 nike

groovy 中 BigDecimal 的默认小数位数是多少?和四舍五入?

因此,当尝试进行计算时:

def x = 10.0/30.0 //0.3333333333
def y = 20.0/30.0 //0.6666666667

基于此,我可以假设它使用比例 10 并向上舍入一半。但很难找到官方文档说明这一点。

最佳答案

可以在官方文档中找到:The case of the division operator

5.5.1. The case of the division operator

The division operators / (and /= for division and assignment) produce a double result if either operand is a float or double, and a BigDecimal result otherwise (when both operands are any combination of an integral type short, char, byte, int, long, BigInteger or BigDecimal).

BigDecimal division is performed with the divide() method if the division is exact (i.e. yielding a result that can be represented within the bounds of the same precision and scale), or using a MathContext with a precision of the maximum of the two operands' precision plus an extra precision of 10, and a scale of the maximum of 10 and the maximum of the operands' scale.

并检查BigDecimalMath.java :

public Number divideImpl(Number left, Number right) {
BigDecimal bigLeft = toBigDecimal(left);
BigDecimal bigRight = toBigDecimal(right);
try {
return bigLeft.divide(bigRight);
} catch (ArithmeticException e) {
// set a DEFAULT precision if otherwise non-terminating
int precision = Math.max(bigLeft.precision(), bigRight.precision()) + DIVISION_EXTRA_PRECISION;
BigDecimal result = bigLeft.divide(bigRight, new MathContext(precision));
int scale = Math.max(Math.max(bigLeft.scale(), bigRight.scale()), DIVISION_MIN_SCALE);
if (result.scale() > scale) result = result.setScale(scale, BigDecimal.ROUND_HALF_UP);
return result;
}
}

关于groovy - groovy中bigdecimal的默认比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32951371/

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