相当于Excel Round函数

时间:2014-01-16 10:42:32

标签: c# excel rounding

我有一个这样的数字:3206.6186522022

我使用了excel表格公式:

ROUND(3206.6186522022;-2)

这给了我:3200

那么如何在c#中实现相同的目标呢?

2 个答案:

答案 0 :(得分:4)

这是一个示例LINQPad程序,演示了一种方法。我通过在Excel中运行所有这些数字来验证它的行为方式相同:

void Main()
{
    Verify(ROUND(3206.618652, 2), 3206.62).Dump();
    Verify(ROUND(3206.618652, 1), 3206.6).Dump();
    Verify(ROUND(3206.618652, 0), 3207).Dump();
    Verify(ROUND(3206.618652, -1), 3210).Dump();
    Verify(ROUND(3206.618652, -2), 3200).Dump();

    Verify(ROUND(3207.618652, 2), 3207.62).Dump();
    Verify(ROUND(3207.618652, 1), 3207.6).Dump();
    Verify(ROUND(3207.618652, 0), 3208).Dump();
    Verify(ROUND(3207.618652, -1), 3210).Dump();
    Verify(ROUND(3207.618652, -2), 3200).Dump();

    Verify(ROUND(3205.618652, 2), 3205.62).Dump();
    Verify(ROUND(3205.618652, 1), 3205.6).Dump();
    Verify(ROUND(3205.618652, 0), 3206).Dump();
    Verify(ROUND(3205.618652, -1), 3210).Dump();
    Verify(ROUND(3205.618652, -2), 3200).Dump();

    Verify(ROUND(-3206.618652, 2), -3206.62).Dump();
    Verify(ROUND(-3206.618652, 1), -3206.6).Dump();
    Verify(ROUND(-3206.618652, 0), -3207).Dump();
    Verify(ROUND(-3206.618652, -1), -3210).Dump();
    Verify(ROUND(-3206.618652, -2), -3200).Dump();

    Verify(ROUND(-3207.618652, 2), -3206.62).Dump();
    Verify(ROUND(-3207.618652, 1), -3206.6).Dump();
    Verify(ROUND(-3207.618652, 0), -3207).Dump();
    Verify(ROUND(-3207.618652, -1), -3210).Dump();
    Verify(ROUND(-3207.618652, -2), -3200).Dump();

    Verify(ROUND(-3205.618652, 2), -3205.62).Dump();
    Verify(ROUND(-3205.618652, 1), -3205.6).Dump();
    Verify(ROUND(-3205.618652, 0), -3206).Dump();
    Verify(ROUND(-3205.618652, -1), -3210).Dump();
    Verify(ROUND(-3205.618652, -2), -3200).Dump();

    Verify(ROUND(3205.4, 0), 3204).Dump();
    Verify(ROUND(3205.6, 0), 3205).Dump();

    Verify(ROUND(-4.4, 0), -4).Dump();
    Verify(ROUND(-4.5, 0), -5).Dump();
    Verify(ROUND(-4.6, 0), -5).Dump();
    Verify(ROUND(4.4, 0), 4).Dump();
    Verify(ROUND(4.5, 0), 5).Dump();
    Verify(ROUND(4.6, 0), 5).Dump();
}

public static string Verify(double value, double expected)
{
    if (Math.Abs(value - expected) < 1e-8)
        return string.Empty;

    return value + " is not equal (enough) to " + expected;
}

public static double ROUND(double value, int decimals)
{
    if (decimals < 0)
    {
        var factor = Math.Pow(10, -decimals);
        return ROUND(value / factor, 0) * factor;
    }
    return Math.Round(value, decimals, MidpointRounding.AwayFromZero);
}

答案 1 :(得分:1)

作为参考,此代码也有效(根据相同的测试数据进行检查):

public static double Round(double value, int digits)
{
    double pow = Math.Pow(10, digits);
    return Math.Truncate(value * pow + Math.Sign(value)*0.5) / pow;
}