How to format a number with thousands separator in C/C++

jstuardo picture jstuardo · Apr 18, 2017 · Viewed 12.2k times · Source

I am trying to do this simple task. Just to format a number using C or C++, but under Windows CE programming.

In this environment, neither inbue nor setlocale methods work.

Finally I did this with no success:

char szValue[10];
sprintf(szValue, "%'8d", iValue);

Any idea?

Answer

Richard Hodges picture Richard Hodges · Apr 18, 2017

Here's one way - create a custom locale and imbue it with the appropriately customised facet:

#include <locale>
#include <iostream>
#include <memory>

struct separate_thousands : std::numpunct<char> {
    char_type do_thousands_sep() const override { return ','; }  // separate with commas
    string_type do_grouping() const override { return "\3"; } // groups of 3 digit
};

int main()
{
    int number = 123'456'789;
    std::cout << "default locale: " << number << '\n';
    auto thousands = std::make_unique<separate_thousands>();
    std::cout.imbue(std::locale(std::cout.getloc(), thousands.release()));
    std::cout << "locale with modified thousands: " << number << '\n';
}

expected output:

default locale: 123456789
locale with modified thousands: 123,456,789