C# 四舍五入到最接近的五
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1531695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Round to nearest five
提问by Martin
I need to round a double to nearest five. I can't find a way to do it with the Math.Round function. How can I do this?
我需要四舍五入到最接近的五。我找不到使用 Math.Round 函数的方法。我怎样才能做到这一点?
What I want:
我想要的是:
70 = 70
73.5 = 75
72 = 70
75.9 = 75
69 = 70
and so on..
等等..
Is there an easy way to do this?
是否有捷径可寻?
回答by Sebastiaan M
Try:
尝试:
Math.Round(value / 5.0) * 5;
回答by Mike Polen
This works:
这有效:
5* (int)Math.Round(p / 5.0)
回答by Max Galkin
Here is a simple program that allows you to verify the code. Be aware of the MidpointRounding parameter, without it you will get rounding to the closest even number, which in your case means difference of five (in the 72.5 example).
这是一个简单的程序,可以让您验证代码。请注意 MidpointRounding 参数,如果没有它,您将四舍五入到最接近的偶数,在您的情况下,这意味着相差五(在 72.5 示例中)。
class Program
{
public static void RoundToFive()
{
Console.WriteLine(R(71));
Console.WriteLine(R(72.5)); //70 or 75? depends on midpoint rounding
Console.WriteLine(R(73.5));
Console.WriteLine(R(75));
}
public static double R(double x)
{
return Math.Round(x/5, MidpointRounding.AwayFromZero)*5;
}
static void Main(string[] args)
{
RoundToFive();
}
}