How can I get a count of the total number of digits in a number?

前端 未结 16 1926
春和景丽
春和景丽 2020-11-28 21:28

How can I get a count of the total number of digits of a number in C#? For example, the number 887979789 has 9 digits.

16条回答
  •  天命终不由人
    2020-11-28 22:00

    Create a method that returns all digits, and another that counts them:

    public static int GetNumberOfDigits(this long value)
    {
        return value.GetDigits().Count();
    }
    
    public static IEnumerable GetDigits(this long value)
    {
        do
        {
            yield return (int)(value % 10);
            value /= 10;
        } while (value != 0);
    }
    

    This felt like the more intuitive approach to me when tackling this problem. I tried the Log10 method first due to its apparent simplicity, but it has an insane amount of corner cases and precision problems.

    I also found the if-chain proposed in the other answer to a bit ugly to look at.

    I know this is not the most efficient method, but it gives you the other extension to return the digits as well for other uses (you can just mark it private if you don't need to use it outside the class).

    Keep in mind that it does not consider the negative sign as a digit.

提交回复
热议问题