我想将数字四舍五入到最接近的 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/