Finding the number of digits of a number in C #
I am trying to write a piece of code in C # to find the numeric digits of an integer number, the code works fine for all numbers (negative and positive), but I have a problem with 10, 100, 1000 and so on, it displays one digit less than the actual number of digits. as 1 for 10 and 2 for 100 ..
long i = 0;
double n;
Console.Write("N? ");
n = Convert.ToInt64(Console.ReadLine());
do
{
n = n / 10;
i++;
}
while(Math.Abs(n) > 1);
Console.WriteLine(i);
source to share
What happened with:
Math.Abs(n).ToString(NumberFormatInfo.InvariantInfo).Length;
Indeed, converting a number to a string is computationally expensive compared to some arithmetic, but difficult to deal with negative numbers, overflow, ...
You need to use Math.Abs
to make sure the sign is not counted and is safe to use NumberFormatInfo.InvariantInfo
so that, for example, certain cultures that use spaces and accents do not change behavior.
source to share
public static int NumDigits(int value, double @base)
{
if(@base == 1 || @base <= 0 || value == 0)
{
throw new Exception();
}
double rawlog = Math.Log(Math.Abs(value), @base);
return rawlog - (rawlog % 1);
}
This NumDigits function is for finding the number of digits for a value in any base. It also includes error handling for invalid input. @C base variable is to make it a shorthand variable (because base is a keyword).
source to share