Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output numbers with digit grouping (1000000 as 1,000,000 and so on)

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.

like image 861
b.buchhold Avatar asked Jul 23 '11 12:07

b.buchhold


People also ask

How do I show 1000000 as 1m in Excel?

In the Format Cells dialog box, on the Number tab, select Custom, then enter #,, “Million” where it says General. (Note: there is a space between the second comma and the double quotation mark.) The displayed value changes from 1000000 to 1 Million.

How do I get MS Excel to display 1 00000 as 100000?

Select the cells which you want to display in thousands. Open the format cell dialogue by pressing Ctrl + 1 or right-click on the cell and select “Format Cells”. On the “Number” tab, click on “Custom” on the left hand side. For “Type” write: #,##0,;-#,##0, and confirm with OK.


1 Answers

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.

like image 161
aroth Avatar answered Nov 15 '22 13:11

aroth