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);

      

+3


source to share


6 answers


Your condition is equal Math.Abs(n) > 1

, but in case 10, you are greater than 1 the first time. You can change this check as >=1

, and this should fix your problem.



do
{
    n = n / 10;
    i++;
}
while(Math.Abs(n) >= 1);

      

+5


source


Use char.IsDigit

:



string input = Console.ReadLine();
int numOfDigits = input.Count(char.IsDigit);

      

+4


source


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.

+2


source


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).

+1


source


Console.ReadLine().Replace(",", String.Empty).Length;

      

0


source


this will count all char in the string

        int amount = 0;
        string input = Console.ReadLine();
        char[] chars = input.ToArray();

        foreach (char c in chars)
        {
            amount++; 
        }
        Console.WriteLine(amount.ToString());
        Console.ReadKey();

      

0


source







All Articles