开发者

Currency formatting with c++

开发者 https://www.devze.com 2023-03-13 16:14 出处:网络
Is there an obvious way to perform currency formatting in C++ ? For example: 197887开发者_如何学JAVA9 would become 1\'978\'879

Is there an obvious way to perform currency formatting in C++ ?

For example: 197887开发者_如何学JAVA9 would become 1'978'879

Thanks


Short answer:

int value = 1978879;
std::cout.imbue(std::locale(""));
std::cout << value << std::endl;

Locales are responsible for formatting. Any stream can be imbued with a locale; by default they use the global locale, which by default is the "C" locale which doesn't use any thousands separators. By creating a locale instance with the empty string as the parameter we use the user's locale, which in your case will likely be Swiss.

You can also specify an explicit locale name, but the names are different depending on your platform (Linux/Windows), and not all systems support all locales.

If you want to get a string, the easiest way is probably to use a stringstream (from the <sstream> header):

std::ostringstream stream;
stream.imbue(std::locale(""));
stream << value;
std::string stringValue = stream.str();

Though you can also use the locale's facets directly, but that's more complicated.

You could also set the global locale, which will be used by all streams (unless they're specifically imbued with a different locale):

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


Take a look at the standard C++ localization library. It's not that straightforward but you can probably achieve that through the num_get/numpunct facets.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号