Using the standard print flag and locale settings:
#include <locale.h> #include <stdio.h> int main() { int value = 1234567; if (!setlocale(LC_ALL, "en_US.UTF-8")) { fprintf(stderr, "Locale not found.\n"); return 1; } printf("%'d\n", value); return 0; }
But using x mod 3 and a Duff device , you can create your own (portable) function:
#include <stdio.h> #include <stdlib.h> char *thousand_sep(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 = thousand_sep(1234567); printf("%s\n", s); free(s); return 0; }
Output:
1,234,567
EDIT:
if i want to do the same in java then ??
Sorry, I don't know Java, maybe useful (in javascript using regex's):
Number.prototype.thousand_sep = function(decs){ var n = this.toFixed(decs).toString().split('.'); n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ','); return n.join('.'); }; ... var x = 1234567; alert(x.thousand_sep(0));
source share