How to Set the Cout Locale to Insert Commas as Thousands Separators

How do you set the cout locale to insert commas as thousands separators?

The default implementation of do_thousands_sep already returns ','. It looks like you should override do_grouping instead. do_grouping returns an empty string by default, which means no grouping. This means groups of three digits each:

string do_grouping() const
{
return "\03";
}

How to format a number with commas as thousands separators?

I used the idea from Kerry's answer, but simplified it since I was just looking for something simple for my specific purpose. Here is what I have:

function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

function test(x, expect) {
const result = numberWithCommas(x);
const pass = result === expect;
console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);
return pass;
}

let failures = 0;
failures += !test(0, "0");
failures += !test(100, "100");
failures += !test(1000, "1,000");
failures += !test(10000, "10,000");
failures += !test(100000, "100,000");
failures += !test(1000000, "1,000,000");
failures += !test(10000000, "10,000,000");
if (failures) {
console.log(`${failures} test(s) failed`);
} else {
console.log("All tests passed");
}
.as-console-wrapper {
max-height: 100% !important;
}

Set thousands separator for C printf

Here is a very simple solution which works on each linux distribution and does not need - as my 1st answer - a glibc hack:


All these steps must be performed in the origin glibc directory - NOT in the build directory - after you built the glibc version using a separate build directory as suggested by this instructions.

My new locale file is called en_AT.

  1. Create in the localedata/locales/ directory from an existing file en_US a new file en_AT .
  2. Change all entries for thousands_sep to thousands_sep "<U0027>" or whatever character you want to have as the thousands separator.
  3. Change inside of the new file all occurrences of en_US to en_AT.
  4. Add to the file localedata/SUPPORTED the line: en_AT.UTF-8/UTF-8 \.
  5. Run in the build directory make localedata/install-locales.
  6. The new locale will be then automatically added to the system and is instantly accessible for the program.

In the C/C++ program you switch to the new thousands separator character with:

setlocale( LC_ALL, "en_AT.UTF-8" );

using it with printf( "%'d", 1000000 ); which produces this output

1'000'000


Remark: When you need in the program different localizations which are determinated while the runtime you can use this example from the man pages where you load the requested locale and just replace the LC_NUMERIC settings from en_AT.

Is there a built-in function that comma-separates a number in C, C++, or JavaScript?

I found this little javascript function that would work (source):

function addCommas(nStr){
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}

Format number with commas in C++

Use std::locale with std::stringstream

#include <iomanip>
#include <locale>

template<class T>
std::string FormatWithCommas(T value)
{
std::stringstream ss;
ss.imbue(std::locale(""));
ss << std::fixed << value;
return ss.str();
}

Disclaimer: Portability might be an issue and you should probably look at which locale is used when "" is passed

How to format a number with commas as thousands separators?

I used the idea from Kerry's answer, but simplified it since I was just looking for something simple for my specific purpose. Here is what I have:

function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function numberWithCommas(x) {
return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

function test(x, expect) {
const result = numberWithCommas(x);
const pass = result === expect;
console.log(`${pass ? "✓" : "ERROR ====>"} ${x} => ${result}`);
return pass;
}

let failures = 0;
failures += !test(0, "0");
failures += !test(100, "100");
failures += !test(1000, "1,000");
failures += !test(10000, "10,000");
failures += !test(100000, "100,000");
failures += !test(1000000, "1,000,000");
failures += !test(10000000, "10,000,000");
if (failures) {
console.log(`${failures} test(s) failed`);
} else {
console.log("All tests passed");
}
.as-console-wrapper {
max-height: 100% !important;
}

Output numbers with digit grouping (1000000 as 1,000,000 and so on)

According to this thread, you can set a locale on your output stream by doing something like:

#include <iostream>
#include <locale>
#include <string>

struct my_facet : public std::numpunct<char> {
explicit my_facet(size_t refs = 0) : std::numpunct<char>(refs) {}
virtual char do_thousands_sep() const { return ','; }
virtual std::string do_grouping() const { return "\003"; }
};

int main() {
std::locale global;
std::locale withgroupings(global, new my_facet);
std::locale was = std::cout.imbue(withgroupings);
std::cout << 1000000 << std::endl;
std::cout.imbue(was);

return 0;
}

Haven't tried it myself but it certainly sounds like a reasonable approach.

How to print a number using commas as thousands separators

Locale unaware

'{:,}'.format(value)  # For Python ≥2.7
f'{value:,}' # For Python ≥3.6

Locale aware

import locale
locale.setlocale(locale.LC_ALL, '') # Use '' for auto, or force e.g. to 'en_US.UTF-8'

'{:n}'.format(value) # For Python ≥2.7
f'{value:n}' # For Python ≥3.6

Reference

Per Format Specification Mini-Language,

The ',' option signals the use of a comma for a thousands separator. For a locale aware separator, use the 'n' integer presentation type instead.



Related Topics



Leave a reply



Submit