您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

内置.Net算法,可将值四舍五入到最接近的10个间隔

内置.Net算法,可将值四舍五入到最接近的10个间隔

类库中没有内置函数可以执行此操作。最接近的是System.Math.Round(),仅用于将Decimal和Double类型的数字四舍五入到最接近的整数值。但是,如果您使用的是.NET 3.5,则可以将语句包装在扩展方法中,这将使您更加整洁地使用该功能

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

如果要针对旧版本的.NET框架进行编程,只需从RoundOff函数删除“ this”,然后按如下所示调用函数

int roundedNumber = ExtensionMethods.RoundOff(236); // returns 240
int roundedNumber2 = ExtensionMethods.RoundOff(11); // returns 10
dotnet 2022/1/1 18:15:51 有467人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶