The following code example is taken from the book
C++23 - The Complete Guide
by Nicolai M. Josuttis,
Leanpub, 2026
The code is licensed under a
Creative Commons Attribution 4.0 International License.
// raw code
#include <iostream>
#include <locale>
#include <print>
#include <string>
// define facet of locale with thousands separator:
struct ThousandsSep : std::numpunct<char> {
char do_decimal_point() const override { return '.'; } // decimal point is dot
char do_thousands_sep() const override { return ','; } // separate with commas
std::string do_grouping() const override { return "\3"; } // every 3 digits
};
int main()
{
// patch std::cout locale to use thousands separator:
static std::locale locThSep{std::cout.getloc(), new ThousandsSep{}};
std::cout.imbue(locThSep);
// use locale to print numeric values:
std::println("{:10} {:16}", 1000000, 123456.9999); // locale not used
std::println("{:10L} {:16L}", 1000000, 123456.9999); // locale not used
std::println(std::cout, "{:10L} {:16L}", 1000000, 123456.9999); // locale used
}