内置 .Net 算法将值四舍五入到最接近的 10 区间 [英] Built in .Net algorithm to round value to the nearest 10 interval

查看:18
本文介绍了内置 .Net 算法将值四舍五入到最接近的 10 区间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C# 中将任何值舍入到 10 区间?例如,如果我有 11,我希望它返回 10,如果我有 136,那么我希望它返回 140.

How to, in C# round any value to 10 interval? For example, if I have 11, I want it to return 10, if I have 136, then I want it to return 140.

我可以轻松地手动完成

return ((int)(number / 10)) * 10;

但我正在寻找一种内置算法来完成这项工作,例如 Math.Round().我不想手工完成的原因是我不想在我的项目中编写相同或相似的代码,即使是像上面这样简单的代码.

But I am looking for an builtin algorithm to do this job, something like Math.Round(). The reason why I won't want to do by hand is that I don't want to write same or similar piece of code all over my projects, even for something as simple as the above.

推荐答案

类库中没有内置函数可以做到这一点.最接近的是 System.Math.Round()仅用于将 Decimal 和 Double 类型的数字四舍五入到最接近的整数值.但是,如果您使用 .NET 3.5,您可以将您的语句封装在扩展方法中,这将使您能够更干净地使用该函数.

There is no built-in function in the class library that will do this. The closest is System.Math.Round() which is only for rounding numbers of types Decimal and Double to the nearest integer value. However, you can wrap your statement up in a extension method, if you are working with .NET 3.5, which will allow you to use the function much more cleanly.

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",然后像这样调用该函数:

If you are programming against an older version of the .NET framework, just remove the "this" from the RoundOff function, and call the function like so:

int roundedNumber = ExtensionMethods.RoundOff(236); // returns 240
int roundedNumber2 = ExtensionMethods.RoundOff(11); // returns 10

这篇关于内置 .Net 算法将值四舍五入到最接近的 10 区间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆