如何用逗号打印双 [英] How to print a double with a comma
问题描述
当用cout打印时,结果字符串是以句点分隔的。
cout< 3.1415<< endl
$> 3.1415
有一种简单的方法强制双面打印逗号?
cout< 3.1415<< endl
$> 3,1415
imbue )code> code> code> code>
与
成员函数返回一个逗号。 locale
获取这样的 locale
方法。您可以使用系统上可用的命名语言环境( std :: locale(fr)
,或许)。或者,您可以派生自己的numpuct,实现 do_decimal_point()
成员。
方法:
模板< typename CharT>
class DecimalSeparator:public std :: numpunct< CharT>
{
public:
DecimalSeparator(CharT Separator)
:m_Separator(Separator)
{}
protected:
CharT do_decimal_point()const
{
return m_Separator;
}
private:
CharT m_Separator;
};
用作:
std :: cout.imbue(std :: locale(std :: cout.getloc(),new DecimalSeparator< char>(',')));
In C++ I've got a float/double variable.
When I print this with for example cout the resulting string is period-delimited.
cout << 3.1415 << endl
$> 3.1415
Is there an easy way to force the double to be printed with a comma?
cout << 3.1415 << endl
$> 3,1415
imbue() cout
with a locale
whose numpunct
facet's decimal_point()
member function returns a comma.
Obtaining such a locale
can be done in several ways. You could use a named locale available on your system (std::locale("fr")
, perhaps). Alternatively, you could derive your own numpuct, implement the do_decimal_point()
member in it.
Example of the second approach:
template<typename CharT>
class DecimalSeparator : public std::numpunct<CharT>
{
public:
DecimalSeparator(CharT Separator)
: m_Separator(Separator)
{}
protected:
CharT do_decimal_point()const
{
return m_Separator;
}
private:
CharT m_Separator;
};
Used as:
std::cout.imbue(std::locale(std::cout.getloc(), new DecimalSeparator<char>(',')));
这篇关于如何用逗号打印双的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!