如何在 C# 中将任何值四舍五入到 10 区间?例如,如果我有 11,我希望它返回 10,如果我有 136,那么我希望它返回 140。
我可以很容易地用手做
return ((int)(number / 10)) * 10;
但我正在寻找一种内置算法来完成这项工作,例如 Math.Round()。我不想手工完成的原因是我不想在我的所有项目中都编写相同或相似的代码,即使是像上面这样简单的代码。
最佳答案
类库中没有内置函数可以执行此操作。最接近的是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
关于c# - 内置 .Net 算法将值四舍五入到最接近的 10 区间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/274439/