default scale of bigdecimal in groovy

喜欢而已 提交于 2019-12-23 12:47:06

问题


What is the default scale of BigDecimal in groovy? And Rounding?

So when trying to do calculations:

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

Base on this, I can assume that it uses scale 10 and rounding half up. Having trouble finding an official documentation saying that though.


回答1:


You can find it in the official documentation: 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.

And check it in 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;
    }
}


来源:https://stackoverflow.com/questions/32951371/default-scale-of-bigdecimal-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!