C++ Utilities
Loading...
Searching...
No Matches
thousands.h
Go to the documentation of this file.
1#pragma once
2// SPDX-FileCopyrightText: 2025 Nessan Fitzmaurice <nzznfitz+gh@icloud.com>
3// SPDX-License-Identifier: MIT
4
9
10#include <iostream>
11#include <locale>
12#include <string>
13
14namespace utilities {
15
17struct commas_facet : std::numpunct<char> {
18 using numpunct::numpunct;
19 char do_thousands_sep() const override { return ','; }
20 std::string do_grouping() const override { return "\003"; }
21};
22
23// We do our own memory management for the commas_facet (set the refs arg to 1).
24static commas_facet our_commas_facet{1};
25
26// NOTE: GCC on the Mac (or more accurately GCC's libstdc++) is poor at handling std::locale.
27// The only locale it seems to know about is "C" or "POSIX"
28// The stdlib for clang (libc++) seems to be much more compliant.
29static const std::locale default_locale{"C"};
30static const std::locale commas_locale(default_locale, &our_commas_facet);
31
36inline void
37imbue_stream_with_commas(std::ios_base& strm = std::cout, bool on = true)
38{
39 on ? strm.imbue(commas_locale) : strm.imbue(default_locale);
40}
41
47inline void
49{
50 on ? std::locale::global(commas_locale) : std::locale::global(default_locale);
51}
52
63inline void
65{
67 imbue_stream_with_commas(std::cout, on);
68 imbue_stream_with_commas(std::cerr, on);
69 imbue_stream_with_commas(std::clog, on);
70}
71
72} // namespace utilities
The namespace for the utilities library.
Definition formatter.h:14
void pretty_print_thousands(bool on=true)
Force the global locale & the usual output streams to insert commas into large numbers.
Definition thousands.h:64
void imbue_global_with_commas(bool on=true)
Force the global locale to insert commas into large numbers so that 23456.7 is printed as 23,...
Definition thousands.h:48
void imbue_stream_with_commas(std::ios_base &strm=std::cout, bool on=true)
Force a stream to insert commas into large numbers for readability so that 23456.7 is printed as 23,...
Definition thousands.h:37
A std::numpunct facet that puts the commas in the thousand spots so 10000.5 -> 10,...
Definition thousands.h:17