舍入小数到最接近的0.05?

时间:2010-02-10 09:51:43

标签: c#

嘿伙计们,我如何在c#中将小数点数舍入到最接近的0.05美分?

例如3.44美元将四舍五入至3.45美元或3.48美元至3.50美元

我玩过math.round()虽然没有想到这一点。

3 个答案:

答案 0 :(得分:18)

之前已多次询问

尝试Math.Round(val*20)/20

请参阅round 0.05

答案 1 :(得分:2)

以下是我编写的一些方法,它们总是向上或向下舍入到任何值。

        public static Double RoundUpToNearest(Double passednumber, Double roundto)
    {

        // 105.5 up to nearest 1 = 106
        // 105.5 up to nearest 10 = 110
        // 105.5 up to nearest 7 = 112
        // 105.5 up to nearest 100 = 200
        // 105.5 up to nearest 0.2 = 105.6
        // 105.5 up to nearest 0.3 = 105.6

        //if no rounto then just pass original number back
        if (roundto == 0)
        {
            return passednumber;
        }
        else
        {
            return Math.Ceiling(passednumber / roundto) * roundto;
        }
    }
    public static Double RoundDownToNearest(Double passednumber, Double roundto)
    {

        // 105.5 down to nearest 1 = 105
        // 105.5 down to nearest 10 = 100
        // 105.5 down to nearest 7 = 105
        // 105.5 down to nearest 100 = 100
        // 105.5 down to nearest 0.2 = 105.4
        // 105.5 down to nearest 0.3 = 105.3

        //if no rounto then just pass original number back
        if (roundto == 0)
        {
            return passednumber;
        }
        else
        {
            return Math.Floor(passednumber / roundto) * roundto;
        }
    }

答案 2 :(得分:0)

此代码段仅向上舍入到最接近的0.05

    public static decimal Round(decimal value) {
        var ceiling = Math.Ceiling(value * 20);
        if (ceiling == 0) {
            return 0;
        }
        return ceiling / 20;
    }