简体   繁体   中英

Convert a floating point number to a localized string in C++

How do I convert a floating point number in to a localized string in C++? For example- Suppose I have a floating point number 1.2 then in certain locales it should be converted to 1.2 and in others as 1,2.

Construct a std::locale object with an empty string argument. This will use the locale that is configured for the system:

std::locale cpploc{""};

We can imbue this object into a character stream:

std::cout.imbue(cpploc);

Now, the output will have locale specific decimal point:

std::cout << 1.2; // either 1.2 or 1,2

Localized C++ programs shoud normally do this as the first thing:

std::locale loc("");
std::locale::global(loc);

Then all formatting should happen according to the user-preferred locale in all streams constructed after that point, but not in cin, cout and cerr (these are already constructed imbued withh the C locale). These streams need to be imbued with the user locale separately.

std.::cout.imbue(loc); // etc

Setting up the global locale changes not only formatting but character classification in is... functions and maybe a few other things.

In addition to Eeronika's answer , if you are interested in simply converting it to a string, you have std::stringstream as an option:

#include <sstream>
#include <locale>
#include <string>
//...
std::locale cpploc{""};
std::stringstream ss;

ss.imbue(cpploc);

ss << 1.2;

std::string asString = ss.str();

More on std::locale .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM