How to format monetary values with C ++?

4

I would like to display values formatted as currency, with thousands and cents separators.

I would like, for example, 56000/12 to have 4.666,67 . I can display 4,666.67 . Would there be any way to change . (dot) by , (comma)?

If you want, this is the code I use (the first 11 entries are 5000 and the 12th is 1000):

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

class BRL : public numpunct<char>
{
    protected:

    virtual char do_thousands_sep() const
    {
        return ',';
    }

    virtual std::string do_grouping() const
    {
        return "";
    }
};

int menor5000;
float stop,media,mes,tot,var;
int main(int argc, char* argv[])
{
    setlocale(LC_ALL, "portuguese");

    cout <<"\n\t\tExercício 5\n";
    locale br(locale(), new BRL());
    cout.imbue(br);

    for (menor5000,mes=1,stop=0;stop<12;stop++,mes++)
    {
        cout<<"Digite o valor da venda no " << mes <<"º mês: ";
        cin>>var;
        if (var < 5000)
        menor5000++;
        tot = tot + var;
    }

media = tot / 12;
cout<<"\n\nA media de vendas mensais em 2013 é de R$ " << setiosflags (ios::fixed) << setprecision(2) << media << "\n";
cout << "\nForam realizadas " << menor5000 << " vendas menores que R$ 5,000.00.";

return 0;
system ("pause");
}
    
asked by anonymous 30.05.2014 / 00:32

2 answers

5

Well, you've practically got the answer for yourself. Just modify the class that inherits from numpunct<char> . Implement do_decimal_point to return a comma and make do_thousands_sep return a point. Here's an example:

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

using namespace std;

class CurrencyLocale : public numpunct<char> {
    virtual char do_thousands_sep() const   { return '.'; }
    virtual char do_decimal_point() const   { return ','; }
    virtual std::string do_grouping() const { return ""; }
};

int main() {
    locale currency(locale(), new CurrencyLocale());
    cout.imbue(currency);

    cout << fixed << setprecision(2) << 5654214.54 << endl;
}

Result is:

5.654.214,54
    
30.05.2014 / 03:24
1

There is a method called Replace() , you can work it together with > Find() . Here's a quick example of how to use it:

I changed to respond to Maniero

#include <iostream>
#include <string>

int main ()
{
  using namespace std;

  string str;

  str = "5,000.00";

  str.replace(str.find(','),1,"@");
  str.replace(str.find('.'),1,",");
  str.replace(str.find('@'),1,".");

  cout << ("%s",str);

  return 0;
}
    
30.05.2014 / 00:59