user223506
user223506

Reputation: 105

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

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?

Upvotes: 8

Views: 3320

Answers (1)

David G
David G

Reputation: 96810

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.

Upvotes: 14

Related Questions