舍入到最接近的五

时间:2009-10-07 13:38:10

标签: c# double rounding

我需要将一个双倍舍入到最接近的五。我找不到使用Math.Round函数的方法。我怎么能这样做?

我想要的是什么:

70 = 70
73.5 = 75
72 = 70
75.9 = 75
69 = 70

依旧......

有一种简单的方法吗?

5 个答案:

答案 0 :(得分:111)

尝试:

Math.Round(value / 5.0) * 5;

答案 1 :(得分:44)

这有效:

5* (int)Math.Round(p / 5.0)

答案 2 :(得分:13)

这是一个简单的程序,允许您验证代码。 请注意MidpointRounding参数,如果没有它,您将四舍五入到最接近的偶数,在您的情况下,这意味着差异为5(在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();
        }
    }

答案 3 :(得分:1)

我是这样的:

int test = 5 * (value / 5); 

对于上面的下一个值(第5步),只需添加5。

答案 4 :(得分:1)

你也可以写一个泛型函数:

选项 1 - 方法

public int Round(double i, int v)
{
    return (int)(Math.Round(i / v) * v);
}

并像这样使用它:

var value = Round(72, 5);

选项 2 - 扩展方法

public static double Round(this double value, int roundTo)
{
    return (int)(Math.Round(value / roundTo) * roundTo);
}

并像这样使用它:

var price = 72.0;
var newPrice = price.Round(5);
相关问题