As you print more and more numbers in the screen it may become cumbersome
to count digits just to see is if you are in the range of millions or 100’s of
millions. Visually grouping digits can simmplify things. There is
a pleathora of ways to do this in C++ but the one I find the best is the one provided
by the standand C++ library through the std::numpunct
object. Here is a small example that uses groups digits using commas.
#include <locale>
#include <iostream>
struct separated_format : std::numpunct<char>
{
char do_thousands_sep() const { return ','; }
std::string do_grouping() const { return "\3"; }
};
int main()
{
std::cout << "default locale: " << 12345678 << '\n';
std::cout << "default locale: " << 12345.678 << '\n';
std::cout.imbue(std::locale(std::cout.getloc(), new separated_format));
std::cout << "locale with modified numpunct: " << 12345678 << '\n';
std::cout << "locale with modified numpunct: " << 12345.678 << '\n';
std::cout << "locale with modified numpunct: " << std::fixed<< 12345.678 << '\n';
}
Sample output:
default locale: 12345678
default locale: 12345.7
locale with modified numpunct: 12,345,678
locale with modified numpunct: 12,345.7
locale with modified numpunct: 12,345.678000
Notice that this approach is locale-indepedent and gives the flexibility of choosing your own separator and number of digits to group.