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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,973 questions

51,917 answers

573 users

How to add comma to a number every 3 digits in C

3 Answers

0 votes
#include <stdio.h>
#include <string.h>

int main(void) {
    long n = 84940083567;
    char commas_number[64];

    sprintf(commas_number, "%ld", n);
    
    int length = strlen(commas_number);
    int commas = ( length - 1 ) / 3;
    char *p = &commas_number[length];
    char *commasp = commas_number + length + commas;

    *commasp-- = *p--;
    for (int i = 1; p >= commas_number; i++) {
        *commasp-- = *p--;
        if ( ( i % 3 ) == 0 )
            *commasp-- = ',';
    }
     
    puts(commas_number);
    
    return 0;
}



/*
run:

84,940,083,567

*/

 



answered Nov 5, 2021 by avibootz
edited Nov 5, 2021 by avibootz
0 votes
#include <stdio.h>
#include <locale.h>
 
int main() {
    long double ld = 84940083567;
     
    setlocale(LC_NUMERIC, "");
     
    printf("%'Lf", ld);
 
    return 0;
}
   
   
 
   
/*
run:
   
84,940,083,567.000000
 
*/

 



answered Nov 6, 2021 by avibootz
0 votes
#include <stdio.h>
#include <locale.h>
 
int main() {
    long double ld = 84940083567.041;
     
    setlocale(LC_NUMERIC, "");
     
    printf("%'Lf", ld);
 
    return 0;
}
   
   
 
   
/*
run:
   
84,940,083,567.041000
 
*/

 



answered Nov 6, 2021 by avibootz

Related questions

1 answer 121 views
1 answer 122 views
1 answer 127 views
1 answer 107 views
1 answer 124 views
2 answers 126 views
1 answer 112 views
...