Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将小数点四舍五入到最接近的0.05?_C# - Fatal编程技术网

C# 将小数点四舍五入到最接近的0.05?

C# 将小数点四舍五入到最接近的0.05?,c#,C#,如何将小数点四舍五入到c#中最接近的0.05美分 e、 g将3.44美元四舍五入至3.45美元,或将3.48美元四舍五入至3.50美元 我一直在玩math.round(),但我还没有弄明白这一点。这一点以前已经被问过很多次了 尝试Math.Round(val*20)/20 请看以下是我编写的两种方法,它们总是向上或向下取整到任意值 public static Double RoundUpToNearest(Double passednumber, Double roundto)

如何将小数点四舍五入到c#中最接近的0.05美分

e、 g将3.44美元四舍五入至3.45美元,或将3.48美元四舍五入至3.50美元


我一直在玩math.round(),但我还没有弄明白这一点。

这一点以前已经被问过很多次了

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


请看

以下是我编写的两种方法,它们总是向上或向下取整到任意值

        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;
        }
    }

此代码段仅四舍五入到最接近的0.05

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

对于向下舍入,如果其他人落入此陷阱,请使用
Math.Floor(val*20)/20
。对于瑞士商业舍入:Math.round(val*20,middpointrounding.AwayFromZero)/20;这一轮是0.975比1,而不是0.95。我想只要四舍五入到最接近的数字也会很有用。您可以使用这两种方法,然后检查Math.Abs(结果)中哪一个更接近您的数字