QString::number() 'f' format without trailing zeros

krzych picture krzych · Sep 17, 2012 · Viewed 10k times · Source

I want to convert number to QString with 3 significant digits.

QString::number(myNumber,'f',3);

does the job but remains trailing zeros. How to use it without them.

Also I've tried 'g' and which shouldn't remain those zeros:

QString::number(myNumber,'g',3);

but for example 472.76 is converted to 473. That surprised me. Why is it so with 'g' option?

However I am interested in 'f' format. So the main question is how to do it with 'f' without trailing zeros?

Input -> Desired output

472.76 -> 472.76

0.0766861 -> 0.077

180.00001 -> 180

Answer

Chris picture Chris · Sep 17, 2012

I'm almost embarrassed to post this but it works:

QString toString( qreal num )
{
    QString str = QString::number( num, 'f', 3 );

    str.remove( QRegExp("0+$") ); // Remove any number of trailing 0's
    str.remove( QRegExp("\\.$") ); // If the last character is just a '.' then remove it

    return str;
}

If you're really concerned about the performance using this method you may want to come up with a different solution.