How can I get a count of the total number of digits of a number in C#? For example, the number 887979789 has 9 digits.
Without converting to a string you could try:
Math.Ceiling(Math.Log10(n));
Correction following ysap's comment:
Math.Floor(Math.Log10(n) + 1);
dividing a number by 10 will give you the left most digit then doing a mod 10 on the number gives the number without the first digit and repeat that till you have all the digits
convert into string and then you can count tatal no of digit by .length method. Like:
String numberString = "855865264".toString();
int NumLen = numberString .Length;
Try This:
myint.ToString().Length
Does that work ?
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.
Answers already here work for unsigned integers, but I have not found good solutions for getting number of digits from decimals and doubles.
public static int Length(double number)
{
number = Math.Abs(number);
int length = 1;
while ((number /= 10) >= 1)
length++;
return length;
}
//number of digits in 0 = 1,
//number of digits in 22.1 = 2,
//number of digits in -23 = 2
You may change input type from double
to decimal
if precision matters, but decimal has a limit too.