Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a number from 1123456789 to 1,123,456,789 in C?

How can I in C language format a number from 1123456789 to 1,123,456,789? I tried using printf("%'10d\n", 1123456789); but that doesn't work.

Could you advise anything? The simpler the solution the better.

like image 878
goe Avatar asked Sep 19 '09 23:09

goe


1 Answers

If your printf supports the ' flag (as required by POSIX 2008 printf()), you can probably do it just by setting your locale appropriately. Example:

#include <stdio.h> #include <locale.h>  int main(void) {     setlocale(LC_NUMERIC, "");     printf("%'d\n", 1123456789);     return 0; } 

And build & run:

$ ./example  1,123,456,789 

Tested on Mac OS X & Linux (Ubuntu 10.10).

like image 62
Carl Norum Avatar answered Sep 17 '22 16:09

Carl Norum