Good day!

I just one to ask if there is a function in C++ that can format a currency directly. Example if I have a float of 10000.00, it shoud output 10,000.00. Note the comma separator.

Thank you!

It's pretty easy, if a tad obscure for those unfamiliar with locales in C++:

#include <iomanip>
#include <iostream>
#include <locale>

using namespace std;

int main()
{
    struct group_facet: public std::numpunct<char> {
    protected:
        string do_grouping() const { return "\003"; }
    };

    cout.imbue(locale(cout.getloc(), new group_facet));

    cout << fixed << setprecision(2) << 10000.00 << '\n';
}

thank you deceptikon!

Ive modied the code a little bit. This locale pretty works!

#include<iomanip>
#include<iostream>
#include<locale>
using namespace std;

struct group_facet: public std::numpunct<char> {
protected:
string do_grouping() const { return "\003"; }
};

int main()
{
cout.imbue(locale(cout.getloc(), new group_facet));
cout << fixed << setprecision(2) << 10000.00 << '\n';
cin.get();
}

Oh, and you can also simplify things by using a specific locale that has the grouping for numbers in the way you want. For example, my local locale has a grouping of "/003", so I can simply do this for the same effect:

#include <iomanip>
#include <iostream>
#include <locale>

using namespace std;

int main()
{
    cout.imbue(locale(""));
    cout << fixed << setprecision(2) << 10000.00 << '\n';
}

But that might also be tricky because now you get all of the other locale-specific stuff that comes along with it and not just grouping and thousands separators. If all you want is a specific number grouping and not a full locale change then my first code would be preferrable.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.