Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thousand separator in C++

Tags:

c++

I want to create a string in C++ with the following format:

string + numbersWithFormatAndThousandSeparator + string

I am not sure whether std::string or snprintf() provides format like that especially the thousand separator. Could someone help me with this?

like image 452
Leslieg Avatar asked Nov 12 '10 09:11

Leslieg


People also ask

What is the thousand separator format?

The character used as the thousands separatorIn the United States, this character is a comma (,). In Germany, it is a period (.). Thus one thousand and twenty-five is displayed as 1,025 in the United States and 1.025 in Germany. In Sweden, the thousands separator is a space.

How do you print a number with commas as thousands separators?

You use the format specification language expression '{:,}' to convert the integer number 1000000 to a string with commas as thousand separators. The outer part, the curly brackets '{...}' says to use the number passed into the format() function as a basis of the formatting process.

Which countries use comma as thousand separator?

The decimal separator is also called the radix character. Likewise, while the U.K. and U.S. use a comma to separate groups of thousands, many other countries use a period instead, and some countries separate thousands groups with a thin space.


2 Answers

Fast and easy way:

std::ostringstream ss;
ss.imbue(std::locale("en_US.UTF-8"));
ss << 1033224.23;
return ss.str();

Would return a string "1,033,244.23"

But it requires en_US.UTF-8 locale to be configured on your system.

like image 196
Artyom Avatar answered Sep 21 '22 02:09

Artyom


C++ locale: http://www.cplusplus.com/reference/std/locale/

like image 35
Šimon Tóth Avatar answered Sep 19 '22 02:09

Šimon Tóth