Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

qt

qstring

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

like image 983
krzych Avatar asked Sep 17 '12 12:09

krzych


1 Answers

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.

like image 125
Chris Avatar answered Sep 24 '22 10:09

Chris