Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to count the number of digits in an integer with C

3 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int countDigitsLog10(int value) {
    int num = abs(value);

    // Zero must be handled explicitly
    if (num == 0) {
        return 1;
    }

    // Use floor(log10(n)) + 1
    return (int)floor(log10(num)) + 1;
}

int main() {
    int number = 987654321;

    int digits = countDigitsLog10(number);

    printf("Number: %d\n", number);
    printf("Digit count (log10 method): %d\n", digits);

    return 0;
}



/*
run:

Number: 987654321
Digit count (log10 method): 9

*/

 



answered Jun 6, 2020 by avibootz
edited 5 hours ago by avibootz
0 votes
#include <stdio.h>
#include <string.h>

int main(void) {
    int n = 8593271;
	
	char s[10];
 
    sprintf(s, "%d", n); 
 
	printf("%i\n", strlen(s));
 	
	return 0;
}
  
  
  
  
/*
run:
    
7
    
*/

 



answered Jun 6, 2020 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int countDigitsString(int value) {
    // Convert to string
    char buffer[50] = "";
    sprintf(buffer, "%d", value);

    // If negative, ignore the leading '-'
    if (buffer[0] == '-') {
        return strlen(buffer) - 1;
    }

    return strlen(buffer);
}

int main() {
    int number = -12345;

    int digits = countDigitsString(number);

    printf("Number: %d\n", number);
    printf("Digit count (String method): %d\n", digits);

    return 0;
}



/*
run:

Number: -12345
Digit count (String method): 5

*/

 



answered 5 hours ago by avibootz
...