Integer to price conversion using Qlocate

Asked

Viewed 105 times

1

How can I use QLocate to convert integer into standard Brazilian price form (without rounding up the figures)?

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" 

1 answer

1


This is because you have removed the ',' and the '.' to make an integer. But when you go to print the final amount you do not return with the part of the cents and conversion believes it is 103,083 real and 0 cents.

To solve this by 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"
  • But then what’s the problem. Try adding 11.020,50 + 10,33 returns 11.030,8 and not 11.030,83.

  • I ran the code I posted and it’s coming back "1.030,83".

  • is 11.020,50 + 10,33 with 1.020,50 + 10,33 wheel without error.

  • Actually, I fixed the code. I think it’s right now. I mainly changed the toString()

  • Thank you very much, now it’s worked. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.