QLocale - Validate price

168 Views Asked by At

I'm having trouble validating price.

Example accepted price: 10,00 / 100,00 / 1.000,00

Not accepted: 10 / 100 / 1000.00

Code, but this passing 100 / 10 / 1000.00

 bool ok;
 QLocale::setDefault(QLocale(QLocale::Portuguese, QLocale::Brazil));
 QLocale brazil; // Constructs a default QLocale
 QString text;
 if(ui->price->text().length() <= 2){
   qDebug() << text.sprintf("%6.2f", ui->price->text().toDouble()); //format 50 = 50.00
 }
 brazil.toDouble(ui->price->text(), &ok);
 qDebug() <<  ok;
1

There are 1 best solutions below

0
On

The validation fails, as you would expect, with both Qt 4.8 and latest Qt 5. Check that you can actually set QLocale properly on your platform. brazil.decimalPoint() should return ','

NOTE: You cannot use QString::sprintf if you want locale aware formatting. Use QTextStream and setLocale() explicitly, as it will default to C locale.

#include <QLocale>
#include <QDebug>
#include <QStringList>

int main()
{
 bool ok;
 QLocale::setDefault(QLocale(QLocale::Portuguese, QLocale::Brazil));
 QLocale brazil; // Constructs a default QLocale
 QStringList textlist = QStringList() << "400.00" << "400" << "400,00";
 for (QString text : textlist) {
     brazil.toDouble(text, &ok);
     qDebug() << text << "is" << ok;
 }

 return 0;

}

yields,

"400.00" is false
"400" is true
"400,00" is true