How to print a double with a comma

后端 未结 6 1300
醉话见心
醉话见心 2020-12-15 10:07

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 <         


        
6条回答
  •  既然无缘
    2020-12-15 10:07

    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
    class DecimalSeparator : public std::numpunct
    {
    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(',')));
    

提交回复
热议问题