-3

We all know that we can get numbers of characters in an string using strlen() function, but if I want to get a number of the digits used in an integer, how can I do it?

Like if there is 1000 stored in a variable a and that variable is an integer type, I want to get length of the number and that is 4.

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
Ashish Neupane
  • 193
  • 2
  • 17

3 Answers3

3

If you know the number is positive, or you want the minus sign to be included in the count:

snprintf(NULL, 0, "%d", a);

If you want the number of digits in the absolute value of the number:

snprintf(NULL, 0, "+%d", a) - 1;

The key to both these solutions is that snprintf returns the number of bytes it would have written had the buffer been large enough to write into. Since we're not giving it a buffer, it needs to return the number of bytes which it would have written, which is the size of the formatted number.

This may not be the fastest solution, but it does not suffer from inaccuracies in log10 (if you use log10, remember to round rather than truncate to an integer, and beware of large integers which cannot be accurately converted to a double because they would require more than 53 mantissa bits), and it doesn't require writing out a loop.

rici
  • 234,347
  • 28
  • 237
  • 341
2

What you're asking for is the number of decimal digits. Integers are stored in a binary format, so there's no built-in way of determining that. What you can do to count the decimal digits is count how many times you can divide by 10.

int count = 1;
while (a >= 10) {
    a /= 10;
    count++;
}
dbush
  • 205,898
  • 23
  • 218
  • 273
2

Not really sure if I got your question right, but given your example, as far as I could understand you want to know how many digits there are in a given number (for example: 1 has one digit, 10 has two digits, 100 has three digits, so on...). You can achieve it using something like this:

#include <stdio.h>
int main(void){
    int numberOfDigits = 0, value;
    scanf("%d", &value); //you scan a value
    if (value == 0) 
        numberOfDigits = 1;
    else{
        while (value != 0){
            numberOfDigits++;
            value = value / 10;
        }
     }
     printf("Number of digits: %d\n", numberOfDigits);
     return 0;
}
woz
  • 544
  • 6
  • 22