1

How can we display an integer comma separated in C?

For example if int i=9876543, result should be 9,876,543.

Cœur
  • 37,241
  • 25
  • 195
  • 267
user2430771
  • 1,326
  • 4
  • 17
  • 33
  • The answers in "How to format a number from 1123456789 to 1,123,456,789 in C?" do not provide a portable answer or one that works for all `int` (INT_MIN fails for many). The accepted answer here is portable and works for INT_MIN. – chux - Reinstate Monica Sep 05 '13 at 17:54

2 Answers2

3

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;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
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).

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176