Rounding double values in C#

后端 未结 4 1239
醉话见心
醉话见心 2020-12-05 13:22

I want a rounding method on double values in C#. It needs to be able to round a double value to any rounding precision value. My code on hand looks like:

pub         


        
4条回答
  •  旧时难觅i
    2020-12-05 14:07

    If you actually need to use double just replace it below and it will work but with the usual precision problems of binary floating-point arithmetics.

    There's most certainly a better way to implement the "rounding" (almost a kind of bankers' rounding) than my string juggling below.

    public static decimal RoundI(decimal number, decimal roundingInterval)
    {
       if (roundingInterval == 0) { return 0;}
    
       decimal intv = Math.Abs(roundingInterval);
       decimal modulo = number % intv;
       if ((intv - modulo) == modulo) {
           var temp = (number - modulo).ToString("#.##################");
           if (temp.Length != 0 && temp[temp.Length - 1] % 2 == 0) modulo *= -1;
       }
        else if ((intv - modulo) < modulo)
            modulo = (intv - modulo);
        else
            modulo *= -1;
    
        return number + modulo;
    }
    

提交回复
热议问题