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

前端 未结 16 1877
春和景丽
春和景丽 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:01

    Answers already here work for unsigned integers, but I have not found good solutions for getting number of digits from decimals and doubles.

    public static int Length(double number)
    {
        number = Math.Abs(number);
        int length = 1;
        while ((number /= 10) >= 1)
            length++;
        return length;
    }
    //number of digits in 0 = 1,
    //number of digits in 22.1 = 2,
    //number of digits in -23 = 2
    

    You may change input type from double to decimal if precision matters, but decimal has a limit too.

提交回复
热议问题