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 134 views
1 answer 137 views
1 answer 136 views
1 answer 121 views
1 answer 139 views
2 answers 147 views
1 answer 125 views
...