Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 515
jstuardo Avatar asked Apr 18 '17 21:04

jstuardo


People also ask

How do you format a thousands separator?

The character used as the thousands separatorIn the United States, this character is a comma (,). In Germany, it is a period (.). Thus one thousand and twenty-five is displayed as 1,025 in the United States and 1.025 in Germany. In Sweden, the thousands separator is a space.

Is used as a separator of thousands?

The decimal separator is also called the radix character. Likewise, while the U.K. and U.S. use a comma to separate groups of thousands, many other countries use a period instead, and some countries separate thousands groups with a thin space.


1 Answers

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
like image 122
Richard Hodges Avatar answered Sep 23 '22 01:09

Richard Hodges