不需要库函数实现不依赖语言的RoundUp以及Round(四舍五入)

实现把一个数四舍五入到指定的小数,比如说设置以0.05为四舍五入的基准点(Round)


80.13 四舍五入后变成81.15

81.16 四舍五入后变成81.15 

81.18 四舍五入后变成81.20

思路

将目标值取余(0.05*2)..就得到了小数点第二位之后的数,再分别和(0.05*1.5),(0.05*0.5)做比较, 在它们中间的就近似等于0.05,在边上的话就是等于0.00或者0.10 

相关代码(C#) tax为目标值,standards为四舍五入集数(0.05)

        private decimal RoundingCalculte(decimal tax, decimal standards)
        {
            decimal tempValue = tax % (standards * 2);
            tax = tax - tempValue;
            if ((tempValue >= standards*0.5) && (tempValue <= standards*1.5))
            {
                tempValue = standards;
            }
            else if (tempValue < standards*0.5)
            {
                tempValue = standards-standards;
            }

    else

    {

        tempValue = standards*2;

    }
            tax = tax + tempValue;
            return tax;
        }

RoundUp的原理基本上相同:

80.11 RoundUp后变成81.15

80.16 RoundUp后变成81.20

        private decimal RoundingUpCalculte(decimal tax, decimal standards)
        {
            decimal tempValue = tax % (standards * 2);
            tax = tax - tempValue;
            if (tempValue > standards)
            {
                tempValue = standards * 2M;
            }
            else if (tempValue > 0M && tempValue <= standards)
            {
                tempValue = standards;
            }
            tax = tax + tempValue;
            return tax;
        }

转载于:https://www.cnblogs.com/raphaelli/archive/2012/02/19/2358170.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值