0

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

How can I format a large integral number with commas in C, such that the readability is improved?

222222 should be 222,222 and 44444444 should be 44,444,444.

Community
  • 1
  • 1
hari
  • 9,439
  • 27
  • 76
  • 110

3 Answers3

1

Use the modulus (%) operation and build your own string.

swegi
  • 4,046
  • 1
  • 26
  • 45
1

If you google for "c format thousands separator" then one of the hits is this page http://www.codeguru.com/forum/archive/index.php/t-402370.html
It's C++ though but it should give you an idea of what you can do.

ChrisWue
  • 18,612
  • 4
  • 58
  • 83
1

You do not need to do the formatting yourself; printf in Unix has a ' modifier:

printf("%'d\n", number);

It looks like Visual Studio doesn't support that. This syntax is locale-aware, however.

Jeremiah Willcock
  • 30,161
  • 7
  • 76
  • 78
  • Thanks, I am looking for Linux only, I tried there and it didn't work. I also found this: For some numeric conversions a radix character (`decimal point') or thousands' grouping character is used. The actual character used depends on the LC_NUMERIC part of the locale. The POSIX locale uses `.' as radix character, and does not have a grouping character. Thus, printf("%'.2f", 1234567.89); - results in `1234567.89' in the POSIX locale, in `1234567,89' in the nl_NL locale, and in `1.234.567,89' in the da_DK locale. But how do I find out what is my locale? what is a locale? – hari Mar 17 '11 at 22:17
  • @hari: What was your locale setting (usually, the `LANG` environment variable)? Is it set to something other than `C`? – Jeremiah Willcock Mar 17 '11 at 22:19
  • Jeremiah: I don't see anything. LANG is not set. – hari Mar 17 '11 at 22:21
  • @hari: Look in your environment for the variables `LANG` and `LC_NUMERIC` and see what they are set to. Try setting them to one of the examples you just pasted in (mine is `en_US.UTF-8`). – Jeremiah Willcock Mar 17 '11 at 22:21
  • @hari: If your locale is not set, you get the POSIX locale you mention in your comment, which doesn't have thousands separators. Try one of the other values and see if that changes the behavior. – Jeremiah Willcock Mar 17 '11 at 22:22
  • Jeremiah: I have 2 boxes: linux and freebsd. On linux : LANG=en_US.utf8 and LC_NUMERIC is not set. And on freeBSD both are undefined. BTW, its not working on linux also. – hari Mar 17 '11 at 22:27
  • Jeremiah: thanks for the knowledge. I guess, I would not rely on locale and create my own function. Thanks much. – hari Mar 17 '11 at 22:32
  • @hari: You must execute `setlocale(LC_NUMERIC, "");` at program startup to acquire the locale settings for numerics (or you can use `setlocale(LC_ALL, "");` to acquire all locale settings. – caf Mar 17 '11 at 23:11