Format decimal with comma and Thousand with period

How can I format a float for the Brazilian value(price) format?

Example: in php number_format($float,2,',','.') separates the decimal with a comma and the thousand unit with a period.

 12
Author: Hy-brazil, 2014-03-19

2 answers

Use QLocale

If the formatting you want is used in a certain language, you can format your number by setting Qlocate (English) with the language containing the desired formatting:

// a definição actual em uso
QLocale loc = QLocale::system();

// Recolher a formatação de números utilizada para a língua Portuguesa
QLocale brasil(QLocale::Portuguese);
loc.setNumberOptions(brasil.numberOptions());

// Define como valor por defeito
QLocale::setDefault(loc);

From here the formatting of numbers should already be as it is used by the Portuguese language.

 12
Author: Zuul, 2020-06-11 14:45:34

The solution using the standard C++ library looks like this:

First it is necessary to create a specialization of the std::numpoint class and overwrite two methods in order to implement the specific behavior for our currency.

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

class BRL : public numpunct<char>
{
    protected:

    //separador de milhar
    virtual char do_thousands_sep() const
    {
        return ',';
    }

    //padrão de agrupamento dos milhares, de 3 em 3
    virtual std::string do_grouping() const
    {
        return "\03";
    }
};

Then to use the following is done:

int main(int argc, char* argv[]){
    float _valor = 1022.33;

    //instanciando um locale que utilizará a especialização de numpunct
    locale br(locale(), new BRL());

    //configurar no cout o locale que será utilizado nas formatações
    cout.imbue(br);

    //setprecistion() é necessário para configurar precisão de apenas duas casas decimais
    //fixed é necessário para que o valor não seja impresso como notação científica.
    cout << "R$ " << setprecision(2) << fixed <<  _valor;

    return 0;
}

The output in the console looks like this:

R$ 1,022.33

Full version on ideone .

 6
Author: Fábio, 2014-03-20 16:29:41