当前位置: 首页 > 工具软件 > Roundup > 使用案例 >

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

毛峻
2023-12-01

实现把一个数四舍五入到指定的小数,比如说设置以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

 类似资料: