How can we display an integer comma separated in C?
For example if int i=9876543, result should be 9,876,543.
How can we display an integer comma separated in C?
For example if int i=9876543, result should be 9,876,543.
 
    
     
    
    You can play with LC_NUMERIC and setlocale() or build your own function, something like:
#include <stdio.h>
#include <stdlib.h>
char *fmt(long x)
{
    char s[64], *p = s, *q, *r;
    int len;
    len = sprintf(p, "%ld", x);
    q = r = malloc(len + (len / 3) + 1);
    if (r == NULL) return NULL;
    if (*p == '-') {
        *q++ = *p++;
        len--;
    }
    switch (len % 3) {
        do {
            *q++ = ',';
            case 0: *q++ = *p++;
            case 2: *q++ = *p++;
            case 1: *q++ = *p++;
        } while (*p);
    }
    *q = '\0';
    return r;
}
int main(void)
{
    char *s = fmt(9876543);
    printf("%s\n", s);
    free(s);
    return 0;
}
 
    
    I believe there is no built-in function for that. However you can convert the integer to string and than compute the comma positions depending on the length of the resulting string(tip:first comma will be after strlen(s)%3 digits, avoid leading comma). 
