PDA

View Full Version : Displaying an integer with thousands separator



Jeffb
1st February 2012, 06:07
Hi guys

The Qt documentation says that both of these methods should give me thousands separators i.e.
1. using QString("%L1").arg(integerVal)
2. setting default local to English United states and then using QLocale toString(int);

What am I doing wrong in the following code or is there some other way of getting thousands separators when displaying an int as a string?

Thanks
Jeff


int dataAsInt = index.model()->data(index, Qt::DisplayRole).toInt();
//dataDescription = QString("%L1").arg(dataAsInt); // doesn't work

QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
QLocale aEnglish;
dataDescription = aEnglish.toString(dataAsInt); // doesn't work

Lykurg
1st February 2012, 06:13
?
#include <QtGui>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);

int i = 12657;
qWarning() << QString("%L1").arg(i);
QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
QLocale aEnglish;
qWarning() << aEnglish.toString(i);
return 0;
}

gives me
"12.657"
"12,657"
on my mac.

Jeffb
1st February 2012, 06:26
@Lykurg

Thanks for the speedy reply.
Yep got it sorted. I'm using a custom delegate and my logic was sending down a path that was using the default data.
Out of interest - would you use the first or second method assuming the default locale is the same as the system local?

Jeff

ChrisW67
1st February 2012, 06:53
They both work here (Qt 4.7.4):


#include <QtCore>
#include <QDebug>

int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);

int dataAsInt = 10234;

QString dataDescription = QString("%L1").arg(dataAsInt); // doesn't work
qDebug() << dataDescription; // outputs "10,234"

QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
QLocale aEnglish;
dataDescription = aEnglish.toString(dataAsInt); // doesn't work
qDebug() << dataDescription; // outputs "10,234"

return 0;
}

My default locale is Australia, English with group separator ','.

So, the question is, "How doesn't it work for you?"


Edit: D'oh! I should have looked harder at the preview before posting

Lykurg
1st February 2012, 15:17
Out of interest - would you use the first or second method assuming the default locale is the same as the system local?Well both work the same. Internally %L1 uses the default local as well. So it is just a matter of taste. Since I am lacy (EDIT: Well if my dictionary is right (spitzenartig in german), I am lacy too, but I wanted to write lazy...) I would go for %L1. Beside for me it looks cleaner.

wysota
1st February 2012, 23:57
%L1 makes more sense if the number is only part of your string, e.g.:

QString a = QString("I have %L1 apples").arg(1024);

Jeffb
2nd February 2012, 11:21
Thanks guys.
I agree that %L1 is easier and looks cleaner.

Cheers
Jeff