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
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.
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.
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>(',')));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With