4

I'm trying to write a piece of code in C# to find the number digits of a integer number, the code works perfectly for all numbers (negative and positive) but I have problem with 10, 100,1000 and so on, it shows one less digits than the numbers' actual number of digits. like 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);
samix73
  • 2,802
  • 4
  • 17
  • 29

6 Answers6

6

Your while condition is Math.Abs(n) > 1, but in the case of 10, you are only greater than 1 the first time. You could change this check to be >=1 and that should fix your problem.

do
{
    n = n / 10;
    i++;
}
while(Math.Abs(n) >= 1);
John Koerner
  • 37,428
  • 8
  • 84
  • 134
4

Use char.IsDigit:

string input = Console.ReadLine();
int numOfDigits = input.Count(char.IsDigit);
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
2

What's wrong with:

Math.Abs(n).ToString(NumberFormatInfo.InvariantInfo).Length;

Indeed, converting a number to a string is computationally expensive compared to some arithmetic, but it is hard to deal with negative nubers, overflow,...

You need to use Math.Abs to make sure the sign is not counted, and it is a safe option to use NumberFormatInfo.InvariantInfo so that for instance certain cultures that use spaces and accents, do not alter the behavior.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
1
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 designed to find the number of digits for a value in any base. It also includes error handling for invalid input. The @ with the base variable is to make it a verbatim variable (because base is a keyword).

0
Console.ReadLine().Replace(",", String.Empty).Length;
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Jacob Lambert
  • 7,449
  • 8
  • 27
  • 47
  • 1
    I think the problem with this approach is that some cultures use spaces, accents, dashes, whatever. It is very hard to implement an algorithm that will take all aspects into account. Furthermore the minus sign will count as an additional character. – Willem Van Onsem Dec 14 '14 at 16:58
0

this will count all the char in a string

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

        foreach (char c in chars)
        {
            amount++; 
        }
        Console.WriteLine(amount.ToString());
        Console.ReadKey();
SuncoastOwner
  • 263
  • 2
  • 9
  • 1
    Why do you iterate over an array to simply count? You can replace this with `chars.Length`... And furthermore, you will count spaces, accents, minus sign,... as well. – Willem Van Onsem Dec 14 '14 at 17:01