四舍五入到c#中最近的10位

时间:2013-08-21 05:59:10

标签: 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 ?

我该怎么做?

5 个答案:

答案 0 :(得分:3)

Chris Charabaruk为您提供所需的答案here

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

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

//编辑: 此方法仅适用于int值。您必须根据自己的喜好编辑此方法。 f.e: public static class ExtensionMethods

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

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

Math.Round(value / 10, MidpointRounding.AwayFromZero) * 10

答案 1 :(得分:3)

其他答案也是正确的,但是如果没有Math.Round,你就会这样做:

((int)((17.3 + 5) / 10)) * 10 // = 20
((int)((13.3 + 5) / 10)) * 10 // = 10
((int)((15.0 + 5) / 10)) * 10 // = 20

答案 2 :(得分:0)

试试这个 -

double d1 = 17.3;
int rounded1 = ((int)Math.Round(d/10.0)) * 10; // Output is 20

double d2 = 13.3;
int rounded2 = ((int)Math.Round(d/10.0)) * 10; // Output is 10

答案 3 :(得分:0)

double Num = 16.6;
int intRoundNum = (Convert.ToInt32(Math.Round(Num / 10)) * 10);
Console.WriteLine(intRoundNum);

答案 4 :(得分:0)

如果您想避免在数学库中进行转换或拉取,您还可以使用模数运算符并执行如下操作:

int result = number - (number % 10);
if (number % 10 >= 5)
{
    result += 10;
}

对于您给定的数字:

<头>
数字 处理 结果
13.3 13.3 - (3.3) 10
17.3 17.3 - (7.3) + 10 20
相关问题