代码之家  ›  专栏  ›  技术社区  ›  NomeN

如何打印带有逗号的双精度字符

  •  9
  • NomeN  · 技术社区  · 16 年前

    在C++中,我得到了一个浮点/双变量。

    例如,当我用cout打印时,结果字符串是以句点分隔的。

    cout << 3.1415 << endl
    $> 3.1415
    

    有没有一种简单的方法可以强制用逗号打印double?

    cout << 3.1415 << endl
    $> 3,1415
    
    6 回复  |  直到 10 年前
        1
  •  13
  •   Éric Malenfant    16 年前

    imbue() cout 用一个 locale 谁的 numpunct decimal_point() 成员函数返回一个逗号。

    场所 std::locale("fr") (也许)。或者,您可以派生自己的numpuct,实现 do_decimal_point() 成员。

    第二种方法的示例:

    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;
    };
    

    用作:

    std::cout.imbue(std::locale(std::cout.getloc(), new DecimalSeparator<char>(',')));
    
        2
  •  3
  •   me22    16 年前

    您需要使用不同的语言环境输入流,该语言环境的num_punct(iirc)方面指定了一个逗号。

    如果您的平台区域设置格式使用逗号,则

    cout.imbue(locale(""));
    

    应该足够了。

        3
  •  2
  •   Warren Young    16 年前

    如何设置程序的默认区域设置取决于平台。例如,在POSIX类型的平台上,它使用LANG和LC_*环境变量。

    #include <locale>
    cout.imbue(std::locale("German_germany"));
    

    其想法是强制使用逗号作为小数分隔符的区域设置。您可能需要调整“German_German”字符串,以在特定平台上获得所需的行为。

        4
  •  1
  •   MSalters    16 年前

    准确地说,这是由 std::numpunct<charT>::decimal_point() 价值你可以 imbue() decimal_point()

        5
  •  0
  •   jannep    12 年前

    std::locale imbue() 将在格式化后中断对字符串的任何分析。例如:

    std::ostringstream s;
    std::locale l("fr-fr");
    s << "without locale: " << 1234.56L << std::endl;
    s.imbue(l);
    s << "with fr locale: " << 1234.56L << std::endl;
    std::cout << s.str();
    


    without locale: 1234.56
    with fr locale: 1 234,56

    使用 strtod() 或者第二根弦上类似的东西可能不太管用。。。此外,第二个输出字符串中“1”和“2”之间的空格是不间断的,这使得字符串更漂亮:-)

        6
  •  0
  •   Erich Kuester    8 年前

    很旧的线,但无论如何。。。我在用距离计算结果填充Gtkmm-3.0下的文本条目时遇到问题。为了让事情更清楚,我添加了一个例子,集中了我最近几天读到的几篇文章的智慧:

    #include <locale>
    // next not necessary, added only for clarity
    #include <gtkmm-3.0/gtkmm.h>
    Gtk::Entry m_Text;
    // a distance measured in kilometers
    double totalDistance = 35.45678;
    std::stringstream str;
    // I am using locale of Germany, pay attention to the _
    str.imbue(std::locale("de_DE"));
    // now we have decimal comma instead of point
    str << std::fixed << std::setprecision(4) << std::setw(16) << totalDistance << " km";
    // the wished formatting corresponds to "%16.4f km" in printf
    m_Text.set_text(str.str());