count the digits in an int in csharp

We can use math operations to count the number of digits in an integer. One way to do this is to repeatedly divide the integer by 10, counting the number of times until it becomes 0. Here's the code:

main.cs
int num = 12345;
int count = 0;

while(num != 0)
{
    count++;
    num /= 10;
}

Console.WriteLine("Number of digits: " + count); // Output: Number of digits: 5
162 chars
11 lines

Alternatively, we can convert the integer to a string and count the number of characters:

main.cs
int num = 12345;
int count = num.ToString().Length;

Console.WriteLine("Number of digits: " + count); // Output: Number of digits: 5
133 chars
5 lines

Both of these methods will give the same result.

gistlibby LogSnag