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

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.


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

Will limit the conversion to the significant digits. You'll most always have 3 numbers.

472.76 => 472
4.7276 => 4.72

Try using the formatted printing functions like QString::sprintf. This should give you more control.

QString numStr;
numStr.sprintf("f.3f", myNumber);

Tags:

C++

Qt

Qstring