Question

How can get currency format from double values? The following snippet works fine with integers while it doesn't with doubles?!

#include <locale.h>
#include <iostream>
#include <iomanip>
#include <sstream>

using namespace std;

int main(void)
{
    ostringstream stream;
    stream.imbue(std::locale(""));
    stream << setprecision(3) <<194663.33;
    string stringValue = stream.str();
    cout << stringValue;
    return 0;
}
Was it helpful?

Solution

Something like this:

#include <iostream>
#include <iomanip>

class punct_facet: public std::numpunct<char>
{
    char do_decimal_point() const { return '.'; }
    char do_thousands_sep() const { return ','; }
    std::string do_grouping() const { return "\03"; }
};
void main()
{
    std::cout.imbue(std::locale(std::cout.getloc(), new punct_facet));
    std::cout << std::fixed << std::setprecision(2);
    std::cout << "Formatted number: " << 194663.33 << std::endl;
}

Output:

Formatted number: 194,663.33

You can find more information here:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top