c++ – QString:number with maximum 2 decimal places without trailing zero

c++ – QString:number with maximum 2 decimal places without trailing zero

The documentation is pretty clear about what you should do:

A precision is also specified with the argument format. For the e, E, and f formats, the precision represents the number of digits after the decimal point. For the g and G formats, the precision represents the maximum number of significant digits (trailing zeroes are omitted).

Therefore, use either the g or G format.

main.cpp

#include <QString>
#include <QDebug>

int main()
{
    qDebug() << QString::number(96400.0000001 / 1000.0, g, 5);
    qDebug() << QString::number(96550.0000001 / 1000.0, G, 5);
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Output

96.4
96.55

This returns the formatted number always in fixed (not scientific) notation, and is reasonably efficient:

QString variableFormat(qreal n) { // assumes max precision of 2
    int i = rint(n * 100.0);
    if (i % 100)
        return QString::number(n, f, i % 10 ? 2 : 1);
    else
        return QString::number(i / 100);
}

c++ – QString:number with maximum 2 decimal places without trailing zero

Use QString::number with both f and g. First, use toDouble() on output of f; then use QString::number with default arguments or with g like this.

QString::number(QString::number(number / 1000.0, f, 2).toDouble(), g, 10);

Leave a Reply

Your email address will not be published.