Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding number of digits of a number in C#

Tags:

c#

numbers

digits

I'm trying to write a piece of code in C# to find the number digits of a integer number, the code works perfectly for all numbers (negative and positive) but I have problem with 10, 100,1000 and so on, it shows one less digits than the numbers' actual number of digits. like 1 for 10 and 2 for 100..

    long i = 0;
    double n;
    Console.Write("N? ");
    n = Convert.ToInt64(Console.ReadLine());

    do
    {
        n = n / 10;
        i++;
    }
    while(Math.Abs(n) > 1);
    Console.WriteLine(i);
like image 790
samix73 Avatar asked Dec 12 '22 02:12

samix73


2 Answers

Your while condition is Math.Abs(n) > 1, but in the case of 10, you are only greater than 1 the first time. You could change this check to be >=1 and that should fix your problem.

do
{
    n = n / 10;
    i++;
}
while(Math.Abs(n) >= 1);
like image 68
John Koerner Avatar answered Jan 06 '23 20:01

John Koerner


Use char.IsDigit:

string input = Console.ReadLine();
int numOfDigits = input.Count(char.IsDigit);
like image 35
Amir Popovich Avatar answered Jan 06 '23 20:01

Amir Popovich