Create a method that returns all digits, and another that counts them:
public static int GetNumberOfDigits(this long value)
{
return value.GetDigits().Count();
}
public static IEnumerable<int> GetDigits(this long value)
{
do
{
yield return (int)(value % 10);
value /= 10;
} while (value != 0);
}
This felt like the more intuitive approach to me when tackling this problem. I tried the Log10
method first due to its apparent simplicity, but it has an insane amount of corner cases and precision problems.
I also found the if
-chain proposed in the other answer to a bit ugly to look at.
I know this is not the most efficient method, but it gives you the other extension to return the digits as well for other uses (you can just mark it private
if you don't need to use it outside the class).
Keep in mind that it does not consider the negative sign as a digit.