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.
It is possible to determine the number of digits by using an implicit cast and several if
-conditions. This approach avoids all allocations.
Consider a number like 1—it has 1 digit and this is easy to determine. But for 100, or -100, we want to get the numbers 3 and 4.
1 -> 1 100 -> 3 -100 -> 4
We show 2 methods that both return the same result when passed integer arguments. Both methods count the sign as a digit (character).
string
and then accesses the Length
property on the string
.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
Here we explain how the GetIntegerDigitCount
method is internally implemented. First, the int
parameter is widened to a double
value.
The ToString
version will force an allocation on the managed heap and is likely much slower. But it is more robust.
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.