Format a Number to a specific QString format

I have a question about formatting a decimal number to a certain QString format. Basically, I have an input box in my program that can take any values. I want it to translate the value in this box to the format “+05.30” (based on the value). The value will be limited to +/-99.99.

Some examples include:

.2 –> +00.02

-1.5 –> -01.50

9.9 –> +09.90

I’m thinking of using a converter like this, but it will have some obvious issues (no leading 0, no leading + sign).

QString temp = QString::number(ui.m_txtPreX1->text().toDouble(), 'f', 2);

This question had some similarities, but doesn’t tie together both front and back end padding.

Convert an int to a QString with zero padding (leading zeroes)

Any ideas of how to approach this problem? Your help is appreciated! Thanks!


I don’t think you can do that with any QString method alone (either number or arg). Of course you could add zeros and signs manually, but I would use the good old sprintf:

double value = 1.5;
QString text;
text.sprintf("%+06.2f", value);

Edit: Simplified the code according to alexisdm’s comment.