Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a double with a comma

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 << endl
$> 3.1415

Is there an easy way to force the double to be printed with a comma?

cout << 3.1415 << endl
$> 3,1415
like image 737
NomeN Avatar asked Sep 14 '09 15:09

NomeN


People also ask

How do you put commas in numbers?

First comma is placed three digits from the right of the number to form thousands, second comma is placed next two digits from the right of the number, to mark lakhs and third comma is placed after another next two digits from the right to mark crore, in Indian system of numeration.

How do you print a number with commas as thousands separators in HTML?

The format() method of this object can be used to return a string of the number in the specified locale and formatting options. This will format the number with commas at the thousands of places and return a string with the formatted number.


2 Answers

imbue() cout with a locale whose numpunct facet's decimal_point() member function returns a comma.

Obtaining such a locale can be done in several ways. You could use a named locale available on your system (std::locale("fr"), perhaps). Alternatively, you could derive your own numpuct, implement the do_decimal_point() member in it.

Example of the second approach:

template<typename CharT>
class DecimalSeparator : public std::numpunct<CharT>
{
public:
    DecimalSeparator(CharT Separator)
    : m_Separator(Separator)
    {}

protected:
    CharT do_decimal_point()const
    {
        return m_Separator;
    }

private:
    CharT m_Separator;
};

Used as:

std::cout.imbue(std::locale(std::cout.getloc(), new DecimalSeparator<char>(',')));
like image 108
Éric Malenfant Avatar answered Oct 20 '22 03:10

Éric Malenfant


This is controlled by your program's locale.

How you set a program's default locale depends on the platform. On POSIX type platforms, it's with the LANG and LC_* environment variables, for instance.

You can force a particular locale -- different from the default -- within a C++ program by calling ios::imbue. Something like this might work:

#include <locale>
cout.imbue(std::locale("German_germany"));

The idea is to force a locale where comma is the decimal separator. You might need to adjust the "German_germany" string to get the behavior you want on your particular platform.

like image 20
Warren Young Avatar answered Oct 20 '22 02:10

Warren Young