Integer conversion to price using QLocate

1

How can I use QLocate to convert integer to standard Brazilian price form (without rounding off the values)?

Code:

QString n1 = "1.020,50";
QString n2 = "10,33";

int  valor1 = n1.replace(".","").replace(",","").toInt();
int  valor2 = n2.replace(".","").replace(",","").toInt();

int resultado_int = (valor1 + valor2);
qDebug() << resultado_int; //correto sem arredondar 100383

//converter
QLocale loc = QLocale::system();
QLocale brasil(QLocale::Portuguese);
loc.setNumberOptions(brasil.numberOptions());
QLocale::setDefault(loc);
qDebug() << brasil.toString(resultado_int); //erro return = "103.083" 
    
asked by anonymous 21.03.2014 / 13:15

1 answer

1

This is because you have removed the ',' and '.' to make a whole number. But when you go to print the final value you do not return with the part of the cents and the conversion believes that it is 103,083 reais and 0 cents.

To resolve this, converting to float only at the end:

QString n1 = "11.020,50";
QString n2 = "10,33";

int  valor1 = n1.replace(".","").replace(",","").toInt();
int  valor2 = n2.replace(".","").replace(",","").toInt();

int resultado_int = (valor1 + valor2);
qDebug() << resultado_int; //correto sem arredondar 100383

//converter
QLocale loc = QLocale::system();
QLocale brasil(QLocale::Portuguese);
loc.setNumberOptions(brasil.numberOptions());
QLocale::setDefault(loc);
qDebug() << brasil.toString(resultado_int * 0.01, 'f', 2); // Retorna 11.030,83"
    
21.03.2014 / 13:55