9

While it is easy to write something that does this by myself, I often wondered if there was something like this in iomanip or somewhere. However, I never found something useful. Ideally, it'd be sensitive to locales (e.g. in Germany you'd write 1,234,567.89 as 1.234.567,89) and hence highly superior to building the comma-string by hand.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
b.buchhold
  • 3,837
  • 2
  • 24
  • 33
  • 4
    In Germany we don't have a four digit group before the decimal point. – CodesInChaos Jul 23 '11 at 12:01
  • obviously, this is a typo. i'll correct it. thanks for letting me know – b.buchhold Jul 23 '11 at 12:02
  • Possible duplicate of [How to print a number with a space as thousand separator?](http://stackoverflow.com/questions/2648364/how-to-print-a-number-with-a-space-as-thousand-separator). – Frédéric Hamidi Jul 23 '11 at 12:05
  • Possible duplicate of [How do you set the cout locale to insert commas as thousands separators](http://stackoverflow.com/questions/4728155/how-do-you-set-the-cout-locale-to-insert-commas-as-thousands-separators) – Kenny Meyer Jul 23 '11 at 12:08

1 Answers1

8

According to this thread, you can set a locale on your output stream by doing something like:

#include <iostream>
#include <locale>
#include <string>

struct my_facet : public std::numpunct<char> {
    explicit my_facet(size_t refs = 0) : std::numpunct<char>(refs) {}
    virtual char do_thousands_sep() const { return ','; }
    virtual std::string do_grouping() const { return "\003"; }
};

int main() {
    std::locale global;
    std::locale withgroupings(global, new my_facet);
    std::locale was = std::cout.imbue(withgroupings);
    std::cout << 1000000 << std::endl;
    std::cout.imbue(was);

    return 0;
}

Haven't tried it myself but it certainly sounds like a reasonable approach.

aroth
  • 54,026
  • 20
  • 135
  • 176
  • That's a lot better than my fully handmade version and will solve my problem, because fully automated localization would only be a nice-to-have feature in my particular use case. Still, I wonder if there is a premade/standard solution that has uses certain facets based on a locale. – b.buchhold Jul 23 '11 at 12:13