如何将小数点分隔符设置为逗号? [英] How can I set the decimal separator to be a comma?

查看:39
本文介绍了如何将小数点分隔符设置为逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 pi 读写为 3,141592 而不是 3.141592,因为在许多欧洲国家/地区使用逗号很常见.如何使用 iostreams 完成此任务?换句话说

I would like to read and write pi as 3,141592 instead of 3.141592, as using the comma is common in many European countries. How can I accomplish this with iostreams? In other words

cout << 3.141592;

应该打印

3,141592

到标准输出.

推荐答案

您应该使用 basic_ios::imbue 来设置首选语言环境.

You should use basic_ios::imbue to set the preferred locale.

看看这里:http://www.cplusplus.com/reference/ios/ios_base/imbue/

区域设置允许您使用用户首选的方式,因此如果意大利的计算机使用逗号分隔十进制数字,则在美国仍使用点.使用语言环境是一种很好的做法.

Locales allow you to use the preferred way by the user, so if a computer in Italy uses comma to separate decimal digits, in the US the dot is still used. Using locales is a Good Practice.

但如果您想明确强制使用逗号,请看这里:http://www.cplusplus.com/reference/locale/numpunct/decimal_point/

But if you want to explicitly force the use of the comma, take a look here: http://www.cplusplus.com/reference/locale/numpunct/decimal_point/

这是我刚刚用 g++ 制作的一个小例子,它强制使用 char ','(将分隔符作为模板参数传递只是为了好玩,并不是真正必要的)

Here a small example I just made with g++ which enforces the char ',' (passing the separator as template argument is just for fun, not really necessary)

#include <iostream>
#include <locale>

template <class charT, charT sep>
class punct_facet: public std::numpunct<charT> {
protected:
    charT do_decimal_point() const { return sep; }
};

int main(int argc, char **argv) {
    std::cout.imbue(std::locale(std::cout.getloc(), new punct_facet<char, ','>));
    std::cout << "My age is " << 3.1415 << " lightyears.
";
}

请注意,使用 cout.getloc() 我只覆盖当前设置的语言环境中的一个方面,也就是说,在 cout 的当前语言环境设置中,我只更改标点已完成.

Note that using cout.getloc() I'm overriding just a single facet in the currently set locale, that is, in the current locale settings of cout, I'm changing only how the punctuation is done.

do_decimal_pointstd::numpunct 的虚函数,您可以重新定义它以提供自定义分隔符.numpunct::decimal_point 在打印您的号码时将使用此虚函数.

do_decimal_point is a virtual function of std::numpunct that you can redefine to provide your custom separator. This virtual function will be used by numpunct::decimal_point when printing your number.

这篇关于如何将小数点分隔符设置为逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆