Skip to content

Instantly share code, notes, and snippets.

@benishor
Created April 13, 2023 10:40
Show Gist options
  • Save benishor/508066664ec31b5c1249508d7b9620cd to your computer and use it in GitHub Desktop.
Save benishor/508066664ec31b5c1249508d7b9620cd to your computer and use it in GitHub Desktop.
Using custom locale for number formatting in C++
#include <iostream>
#include <locale>
class comma_numpunct : public std::numpunct<char> {
virtual char do_decimal_point() const {
return ',';
}
virtual char do_thousands_sep() const {
return '.';
}
virtual std::string do_grouping() const {
return "\02";
}
};
int main() {
std::locale comma_locale(std::locale(), new comma_numpunct);
std::cout.imbue(comma_locale); // imbue locale for this stream
std::cout << 1234.234f << std::endl;
// prints out 12.34,23
// ... or ...
std::locale comma_locale(std::locale(), new comma_numpunct);
std::locale::global(comma_locale);
// and from here onwards all streams can imbue the global locale
std::cout.imbue(std::locale());
std::cout << 1234.234f << std::endl;
// prints out 12.34,23
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment