Get number of digits before decimal point

前端 未结 25 1848
独厮守ぢ
独厮守ぢ 2020-12-28 11:53

I have a variable of decimal type and I want to check the number of digits before decimal point in it. What should I do? For example, 467.45 should

25条回答
  •  囚心锁ツ
    2020-12-28 12:16

    Instead of converting to string, you can also divide the number by 10 until it equals 0. Interesting is, that the mathematical operations on decimals are much slower than converting the decimal to a string and returning the length (see benchmarks below).
    This solution does not use the Math-methods that take a double as input; so all operations are done on decimals and no casting is involved.

    using System;
    
    public class Test
    {
        public static void Main()
        {
            decimal dec = -12345678912345678912345678912.456m;
            int digits = GetDigits(dec);
            Console.WriteLine(digits.ToString());
        }
    
        static int GetDigits(decimal dec)
        {
            decimal d = decimal.Floor(dec < 0 ? decimal.Negate(dec) : dec);
            // As stated in the comments of the question, 
            // 0.xyz should return 0, therefore a special case
            if (d == 0m)
                return 0;
            int cnt = 1;
            while ((d = decimal.Floor(d / 10m)) != 0m)
                cnt++;
            return cnt;
        }
    }
    

    Output is 29. To run this sample, visit this link.


    Side note: some benchmarks show surprising results (10k runs):

    • while ((d = decimal.Floor(d / 10m)) != 0m): 25ms
    • while ((d = d / 10m) > 1m): 32ms
    • ToString with Math-double-operations: 3ms
    • ToString with decimal-operations: 3ms
    • BigInt (see answer of @Heinzi): 2ms

    Also using random numbers instead of always the same value (to avoid possible caching of the decimal to string conversion) showed that the string-based methods are much faster.

提交回复
热议问题