类库中没有内置函数可以执行此操作。最接近的是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