c# - 四舍五入到 c# 中最接近的 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 ?

我该怎么做?

最佳答案

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 值。您必须根据自己的喜好编辑此方法。 例如: 公共(public)静态类扩展方法

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

/edit2:正如 corak 所说,你应该/可以使用

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

关于c# - 四舍五入到 c# 中最接近的 10 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18349844/

相关文章:

asp.net - IIS URL 重写 - 如果 URL 包含则忽略

ios - 在 Swift 中的整数后显示 .0

sql - SQL 中四舍五入到 n 个有效数字

c# - 错误 : Does not implement interface member

c# - 检查,任何 LinqToSql 操作后操作成功

c# - 如何在 MVC Razor DropDownList 中使用 Html.Raw?

java整数舍入(除法相关)

c# - 有人知道在线免费数据库吗?

c# - 使用 MVVM 在 WPF 中设置焦点

c# - 如何为ASP.NET网站自定义一个页面的用户控件?