Integer digit count. The number 100 has 3 digits. A C# method can gets the number of digits in an integer like this one. We can avoid the ToString method.
Method info. It is possible to determine the number of digits by using an implicit cast and several if-conditions. This approach avoids all allocations.
Version 2 The second method, GetIntegerDigitCount, uses logic to determine how many characters the integer would have if it were a string.
using System;
class Program
{
static void Main()
{
// Write number of digits in the integers using two methods.
int[] values = {1, 100, -100};
foreach (int i in values)
{
int result1 = GetIntegerDigitCountString(i);
int result2 = GetIntegerDigitCount(i);
Console.WriteLine(i + "=" + result1 + " " + result2);
}
}
static int GetIntegerDigitCountString(int value)
{
// Version 1: get digit count with ToString.
return value.ToString().Length;
}
static int GetIntegerDigitCount(int valueInt)
{
// Version 2: use if-statements.
double value = valueInt;
int sign = 0;
if (value < 0)
{
value = -value;
sign = 1;
}
if (value <= 9)
{
return sign + 1;
}
if (value <= 99)
{
return sign + 2;
}
if (value <= 999)
{
return sign + 3;
}
if (value <= 9999)
{
return sign + 4;
}
if (value <= 99999)
{
return sign + 5;
}
if (value <= 999999)
{
return sign + 6;
}
if (value <= 9999999)
{
return sign + 7;
}
if (value <= 99999999)
{
return sign + 8;
}
if (value <= 999999999)
{
return sign + 9;
}
return sign + 10;
}
}1=1 1
100=3 3
-100=4 4
Method explanation. Here we explain how the GetIntegerDigitCount method is internally implemented. First, the int parameter is widened to a double value.
And This allows us to convert it to a positive value without losing information.
Then We test it against zero, and if it is negative, we set the sign variable to 1 and make it positive.
Finally We test against the constants (9, 99, 999) to determine its positive length. We return the sum of characters in the string.
Performance note. The ToString version will force an allocation on the managed heap and is likely much slower. But it is more robust.
A summary. We computed the number of digits in an integer using mathematical logic only. An if-statement can determine digit count. We also use the ToString method.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.