PDA

View Full Version : Convert double to QTrsing with a fixed number of decimals



Yes
25th December 2012, 12:58
I am converting the time since the start of the program to a QString continuously which I print in the status bar. I print it like this:



ui->statusBar->showMessage("Time: " + QString::number(system.get_time(), ) + " s");


I have already changed the font to a fixed width font ("Courier"), but since the number of decimals after the decimal point keeps changing, the unit ("s") keeps moving forth and back all the time and is barely readable. The maximum number of decimals printed at the same time seems to be 6 though. How can I most easily make sure that 6 decimals are always printed, even if the last of the decimals are zeros?

wysota
25th December 2012, 13:33
Pseudocode:
while number of decimals < 6: string += '0'

Zlatomir
25th December 2012, 13:40
You can use 'f' instead of default 'g' for format and it should work the way you want:

QString s = QString::number(9.56, 'f', 6); //s will be "9.560000"

lanz
25th December 2012, 13:44
You can use:
QString::number (1.0, 'f', 6);

Or better use:
QString("%L1").arg (1.0, 0, 'f', 6);
It yields locale-appropriate representation, and also enables you to pad your string on the left side too by specifying fieldWidth:
QString("%L1").arg (1.0, 12, 'f', 6, '0');

Yes
30th December 2012, 13:05
Thanks! I used Zlatomir's method, it was enough for me. Maybe if I would need to fix the number of digits before the decimal point as well I would use lanz' method (because that's what I guess it's for).

ChrisW67
30th December 2012, 20:37
Lanz's locale-specific tweak also ensure the number is displayed with the appropriate decimal point, thousands separator (i.e. '.' or ','), sign character etc. for the users' locale. See QLocale. The field width and fill character can be used without the locale specific stuff.

Yes
30th December 2012, 22:10
Ah, I see.