thousand separator-help

I have a very complicated code, with many outputs which are print out on a text file, now I want to use thousand separator for numbers?
how should I do this?
Use a custom numpunct facet.
http://www.cplusplus.com/reference/std/locale/numpunct/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <locale>
#include <iomanip>

int main()
{
    struct my_numpunct : std::numpunct<char>
    {
        protected :
           virtual char do_thousands_sep() const override { return ',' ; }
           virtual std::string do_grouping() const override { return "\03\02" ; }
    };

    std::cout.imbue( std::locale( std::cout.getloc(), new my_numpunct ) ) ;
    std::cout << std::fixed << std::setprecision(2) << 1234567.896 << '\n' ; // 12,34,567.90
}

Here is a subroutine that displays your numbers with commas, though it doesn't display anything after the point, so the above example would show only 1,234,567. Hope that's enough.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iomanip>

void commaInsert(unsigned _int64 v)
{
	//base case
	if (v <= 0)
	{
		return;
	}
	//main logic
	commaInsert(v/1000);
	if(v >=1000)
	{
		cout<<",";
		cout<<setfill('0')<<setw(3)<<(v%1000); //stores on stack waiting for return
	}
	else
		cout<<(v%1000); //stores on stack waiting for return
	return;
}
On most systems, the U.S./English settings are present by default, so this may be sufficient:


1
2
3
4
5
6
7
8
9
10
11
12
#include <locale>
#include <iostream>
int main()
{
#ifdef _WIN32
     std::locale loc("English_America");
#else
     std::locale loc("en_US.UTF8");
#endif
     std::cout.imbue(loc); // or use your ofstream object
     std::cout << std::fixed << 1234567.89 << '\n';
}
Last edited on
Keep in mind that messing with locales is a system-dependent thing, especially on Windows. Cubbi's code, for example, will not work with GCC out of the box.

This is the frustrating about the C++ locale specification -- it leaves the names of locales to implementation. Sure, there are reasons that it was done that way, but I think it was a mistake. (It would take very little to specify a standard that could be mapped to individual implementations...)
Topic archived. No new replies allowed.