在 C# 中四舍五入到最接近的 10 位

4 c# asp.net rounding

我想将数字四舍五入到最近10的位置。例如,像这样的数字17.3被四舍五入为20.0。并希望允许三位有效数字。意思是作为过程的最后一步四舍五入到最接近的十分之一。

样品

    the number is 17.3 ,i want round to 20 ,

    and this number is 13.3 , i want round to 10 ?
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点 ?

Mar*_*rco 5

Chris Charabaruk在这里给你你想要的答案

为了进入核心,这是他作为扩展方法的解决方案:

public static class ExtensionMethods
{
    public static int RoundOff (this int i)
    {
        return ((int)Math.Round(i / 10.0)) * 10;
    }
}

int roundedNumber = 236.RoundOff(); // returns 240
int roundedNumber2 = 11.RoundOff(); // returns 10
Run Code Online (Sandbox Code Playgroud)

//edit: 此方法仅适用于 int 值。您必须根据自己的喜好编辑此方法。fe: 公共静态类 ExtensionMethods

{
    public static double RoundOff (this double i)
    {
       return (Math.Round(i / 10.0)) * 10;
    }
}
Run Code Online (Sandbox Code Playgroud)

/edit2:正如科拉克所说,你应该/可以使用

Math.Round(value / 10, MidpointRounding.AwayFromZero) * 10
Run Code Online (Sandbox Code Playgroud)