Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make that a float use comma and not point?

Tags:

c++

visual-c++

I want to make a operator<< that use the local setings or if not at least manualy be able to change the use of "." for decimal separator to ",". I will like a way of making that the stream (iostream, fstream, etc) to do this and not to create the string and then print it.

Is this possible?

like image 562
user223506 Avatar asked Jul 17 '13 14:07

user223506


1 Answers

You can imbue a numpunct facet onto your stream. I believe something like this should work for you:

template <typename T>
struct comma_separator : std::numpunct<T>
{
    typename std::numpunct<T>::char_type do_decimal_point() const
    {
        return ',';
    }
};

template <typename T>
std::basic_ostream<T>& comma_sep(std::basic_ostream<T>& os)
{
    os.imbue(std::locale(std::locale(""), new comma_separator<T>));
    return os;
}

int main()
{
    std::cout << comma_sep << 3.14; // 3,14
}

Here is a demo.


A shorter solution, which uses a European locale:

std::cout.imbue(
    std::locale(
        std::cout.getloc(), new std::numpunct_byname<char>("de_DE.utf8")));

But ultimately it depends on the locales that your system provides.

like image 85
David G Avatar answered Dec 15 '22 01:12

David G