morandalex
morandalex

Reputation: 95

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.

Upvotes: 2

Views: 2837

Answers (2)

Christian Hackl
Christian Hackl

Reputation: 27528

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.

Upvotes: 2

DeepCoder
DeepCoder

Reputation: 840

Your issue is that std::to_string() uses the C locale libraries. It appears that "de_DE" is not a valid locale on your machine (or Coliru for that matter), leading to the default C locale being used and using .. The solution is to use "de_DE.UTF-8". As an aside, using "" for std::locale will not always produce commas; instead, it will depend on the locale set for your machine.

Upvotes: 2

Related Questions