我怎样才能设置小数点分隔符为逗号? [英] How can I set the decimal separator to be a comma?

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

问题描述

我想将 pi 读写为 3,141592 而不是 3.141592 ,因为使用逗号在很多欧洲国家很常见。我如何用 iostream s来完成这个任务?换句话说,

  cout<< 3.141592; 

应该打印

  3,141592 

转换为标准输出。

解决方案您应该使用 basic_ios :: imbue 设置首选区域设置。



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



语言环境允许您使用用户首选的方式,所以如果意大利的一台电脑用逗号分隔十进制数字,在美国这个点仍然被使用。使用语言环境是一个好习惯。



但是如果你想显式强制使用逗号,请看这里:
http://www.cplusplus.com/reference/locale/numpunct/decimal_point/



这里有一个小例子,我用g ++强制实现了char','(把分隔符作为模板参数传递,只是为了好玩,不是真的有必要)

  #include< iostream> 
#include< locale>

模板< class charT,charT sep>
class punct_facet:public std :: numpunct< charT> {
保护:
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<< 我的年龄是< 3.1415<< lightyears.\\\
;

$ / code>

请注意,使用 cout.getloc() code>我只是重写当前设置的区域设置中的一个方面,也就是说,在cout的当前区域设置中,我只更改标点符号的方式。



do_decimal_point 是一个虚拟函数 std :: numpunct ,您可以重新定义以提供您的自定义分隔器。打印你的号码时,这个虚拟函数将被 numpunct :: decimal_point 使用。


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;

should print

3,141592

to standard output.

解决方案

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

Take a look here: 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.

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/

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.\n";
}

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_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天全站免登陆