首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >取整BigDecimal取决于第十位的值

取整BigDecimal取决于第十位的值
EN

Stack Overflow用户
提问于 2016-10-13 09:22:50
回答 2查看 89关注 0票数 0

假设我有一个BigDecimal,它可以是任意数量的值。如果第十位的值小于3(即12.2,我希望向下舍入为12)。如果第十位的值大于或等于3(即11.3),我希望将第十位的值向上舍入为5 (所以这里的值最终将是11.5)。BigDecimal是否有现有的功能,可以方便地实现这一点。如果不是,还有什么好的方法来达到这个目的呢?

EN

回答 2

Stack Overflow用户

发布于 2016-10-13 09:53:00

您可以创建自己的BigDecimal版本并覆盖round方法,但这只会在使用该方法时有所帮助。对于它自然进行的舍入(当进行正常的数学运算时),那么没有简单的方法来改变它已经提供的舍入行为。如果您查看一下BigDecimal实现,就会发现许多进行舍入的方法都是静态的,因此您无法覆盖它们。

下面是如何重写round方法。

代码语言:javascript
复制
class MyDecimal extends BigDecimal {

    public MyDecimal(BigInteger val) {
        super(val);
    }

    @Override
    public BigDecimal round(MathContext mc) {

        /* implement your rounding algorithm here*/
    }

}
票数 1
EN

Stack Overflow用户

发布于 2016-10-14 05:42:16

您可以首先使用setScale()BigDecimal缩放到10位十进制数字。然后,您可以操作unscaledValue()的最后一位数

代码语言:javascript
复制
public class BigDecimalRounder
{
    public static BigDecimal roundToNearestHalf(BigDecimal value)
    {
        // Scale to 10 decimal digits and get the underlying BigInteger:
        BigInteger digits = value.setScale(10, BigDecimal.ROUND_HALF_UP).unscaledValue();

        // Act upon the last digit of the BigInteger:
        BigInteger lastDigit = digits.mod(BigInteger.TEN);
        int intDigit = lastDigit.intValue();
        BigInteger newDigit;

        if (intDigit >= 0 && intDigit <= 2)
            newDigit = BigInteger.ZERO;          // round down
        else if (intDigit >= 3 && intDigit <= 7)
            newDigit = BigInteger.valueOf(5);    // round to nearest 5
        else
            newDigit = BigInteger.TEN;           // round up

        // Assemble a new BigInteger, removing the original last digit and 
        // adding the new one (either 0, 5 or 10) 
        BigInteger newValue = digits.subtract(lastDigit).add(newDigit);

        //Assemble a new BigDecimal with the modified digits.
        return new BigDecimal(newValue, 10);
    }

    public static void main(String[] args)
    {
        BigDecimal mainValue = new BigDecimal("1.2399997990");
        BigDecimal addend = BigDecimal.ONE.movePointLeft(10);
        for (int i = 1; i <= 12; i++)
        {
            System.out.println("" + mainValue + " --> " + roundToNearestHalf(mainValue));
            mainValue = mainValue.add(addend);
        }
    }

}

输出:

代码语言:javascript
复制
1.2399997990 --> 1.2399997990
1.2399997991 --> 1.2399997990
1.2399997992 --> 1.2399997990
1.2399997993 --> 1.2399997995
1.2399997994 --> 1.2399997995
1.2399997995 --> 1.2399997995
1.2399997996 --> 1.2399997995
1.2399997997 --> 1.2399997995
1.2399997998 --> 1.2399998000
1.2399997999 --> 1.2399998000
1.2399998000 --> 1.2399998000
1.2399998001 --> 1.2399998000
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40010823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档