Thousand separator in C++
Asked Answered
c++
S

4

12

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?

Seaward answered 12/11, 2010 at 9:35 Comment(0)
G
8

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.

Gerick answered 12/11, 2010 at 16:50 Comment(1)
THat worked for me on one machine, but failed on another ("locale not found" or something. Then I tried simply ss.imbue(std::locale("")); . This worked. I think that "" selects the default locale for your system, and hopefully that'll be what you, and your users, want. Note that locale() failed (no thousands separator).Portrait
R
2

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

Romansh answered 12/11, 2010 at 9:37 Comment(0)
L
0

Information (including the separator for thousands) for formatting numeric values is available in the <clocale> header. That header provides a lconv struct which has the information you need. In particular, the struct features a char *thousands_sep member which might be just what you need.

See the struct lconv documentation for all the details.

Lumenhour answered 12/11, 2010 at 9:41 Comment(0)
D
0

There are many ways to properly format a number in C++. Check out this article for some of them (boost::lexical_cast is my personal favorite): http://www.cplusplus.com/articles/numb_to_text/

Duvall answered 12/11, 2010 at 9:52 Comment(2)
Unless I'm missing how, lexical_cast doesn't do thousands separators?Pendentive
AFAIK lexical_cast uses the current global locale. So if thousand separators are present in the locale, they will be parsed/formatted properly.Duvall

© 2022 - 2024 — McMap. All rights reserved.