How to print a double with a comma

后端 未结 6 1331
醉话见心
醉话见心 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:15

    Old thread, but anyway ... One should be aware that using a std::locale makes the string "pretty", complete with correct decimal point, thousands separators and what not, depending on the platform and locale. Most probably, using imbue() will break any parsing of the string after it's formatted. For example:

    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();
    

    Gives the following output:
    without locale: 1234.56
    with fr locale: 1 234,56

    Using strtod() or similar on the second string probably won't work very well ... Also, the space between "1" and "2" in the second output string is a non-breaking one, making the string even prettier :-)

提交回复
热议问题