Stochastic Nonsense

Put something smart here.

Thousands Separator in Printf in C++

I’ve unfortunately been writing some C++. It’s the crappiest language in the world. I just wasted 90 perfectly good minutes attempting to put thousands separators in numbers that I’m printf ing. If you naively read the man pages, it looks easy — just include ' in your format specifier. Unfortunately, the hidden requirement is that you call this earlier in your code:

1
2
3
4
5
6
7
#include<locale.h>
[...]
setlocale(LC_ALL, "");

// then
unsigned int x = 12345u;
printf("%'8u\n", x);  // -> 12,345 as desired

Edit: I was developing under OS X with XCode 3.2.6.

1
2
3
4
$ sw_vers
ProductName:  Mac OS X
ProductVersion:   10.6.7
BuildVersion: 10J4138

I also verified this works under linux, or at least centos. The man page for printf doesn’t even mention apostrophe as an option, but it still works as long as you call setlocale.

1
2
3
4
$ uname -r
2.6.18-164.6.1.el5.centos.plus
$ cat /proc/version 
Linux version 2.6.18-164.6.1.el5.centos.plus (mockbuild@builder10.centos.org) (gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)) #1 SMP Wed Nov 4 09:31:39 EST 2009