Search code examples
c++printinglocalefstreamcout

c++ How to print in a file a double decimal number with comma(instead of dot)


I need to print a csv file with numbers. When the file is printed , I have numbers with dots, but I need them with commas.

Here an example. If I print this number in terminal using locale method, I obtain a number with comma, but in the file I have the same number but with dot. I do not understand why. How could I do?

#include <iostream>
#include <locale>
#include <string>     // std::string, std::to_string
#include <fstream>
using namespace std;
int main()
{
    double x = 2.87;
    std::setlocale(LC_NUMERIC, "de_DE");
    std::cout.imbue(std::locale(""));
    std::cout << x << std::endl;
    ofstream outputfile ("out.csv");
    if (outputfile.is_open())
        {
            outputfile  <<to_string(x)<<"\n\n";
        }
    return 0;
}

Thanks in advance.


Solution

  • Locales are system-specific. You probably just made a typo; try "de-DE", which will probably work (at least it does on my Windows).


    However, if your program is not inherently German-centric, then abusing the German locale just for the side effect of getting a specific decimal point character is bad programming style, I think.

    Here is an alternative solution using std::numpunct::do_decimal_point:

    #include <string>
    #include <fstream>
    #include <locale>
    
    struct Comma final : std::numpunct<char>
    {
        char do_decimal_point() const override { return ','; }
    };
    
    int main()
    {
        std::ofstream os("out.csv");
        os.imbue(std::locale(std::locale::classic(), new Comma));
        double d = 2.87;
        os << d << '\n'; // prints 2,87 into the file
    }
    

    This code specifically states that it just wants the standard C++ formatting with only the decimal point character replaced with ','. It makes no reference to specific countries or languages, or system-dependent properties.