如何用逗号打印双 [英] How to print a double with a comma

查看:150
本文介绍了如何用逗号打印双的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,我有一个float / double变量。



当用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屋!

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