Truncate number of digit of double value in C#

后端 未结 12 782
死守一世寂寞
死守一世寂寞 2020-12-30 04:35

How can i truncate the leading digit of double value in C#,I have tried Math.Round(doublevalue,2) but not giving the require result. and i didn\'t find any other method in M

12条回答
  •  我在风中等你
    2020-12-30 04:39

    There are a lot of answers using Math.Truncate(double). However, the approach using Math.Truncate(double) can lead to incorrect results. For instance, it will return 5.01 truncating 5.02, because multiplying of double values doesn't work precisely and 5.02*100=501.99999999999994

    If you really need this precision, consider, converting to Decimal before truncating.

    public static double Truncate(double value, int precision)
    {
        decimal power = (decimal)Math.Pow(10, precision);
        return (double)(Math.Truncate((decimal)value * power) / power);
    }
    

    Still, this approach is ~10 times slower.

提交回复
热议问题