加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

groovy中默认的bigdecimal标度

发布时间:2020-12-14 16:23:45 所属栏目:大数据 来源:网络整理
导读:groovy中BigDecimal的默认比例是多少?和舍入? 所以在尝试进行计算时: def x = 10.0/30.0 //0.3333333333def y = 20.0/30.0 //0.6666666667 基于此,我可以假设它使用了比例10并且舍入了一半. 虽然找不到官方文件,却很难找到. 解决方法 您可以在官方文档中
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;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读