Convert more accurately decimal numbers to text.

This commit is contained in:
sledgehammer999 2014-01-21 01:47:30 +02:00
parent 4d3672f894
commit 441d1d08ba
10 changed files with 39 additions and 48 deletions

View file

@ -30,6 +30,8 @@
#include "misc.h"
#include <cmath>
#include <QUrl>
#include <QDir>
#include <QFileInfo>
@ -38,6 +40,7 @@
#include <QDebug>
#include <QProcess>
#include <QSettings>
#include <QLocale>
#ifdef DISABLE_GUI
#include <QCoreApplication>
@ -255,9 +258,7 @@ QString misc::friendlyUnit(qreal val, bool is_speed) {
if (i == 0)
ret = QString::number((long)val) + " " + QCoreApplication::translate("misc", units[0].source, units[0].comment);
else
/* HACK because QString rounds up. Eg QString::number(0.999*100.0, 'f' ,1) == 99.9
** but QString::number(0.9999*100.0, 'f' ,1) == 100.0 */
ret = QString::number((int)(val*10)/10.0, 'f', 1) + " " + QCoreApplication::translate("misc", units[i].source, units[i].comment);
ret = accurateDoubleToString(val, 1) + " " + QCoreApplication::translate("misc", units[i].source, units[i].comment);
if (is_speed)
ret += QCoreApplication::translate("misc", "/s", "per second");
return ret;
@ -572,3 +573,18 @@ bool misc::naturalSort(QString left, QString right, bool &result) { // uses less
return false;
}
#endif
QString misc::accurateDoubleToString(double n, int precision) {
/* HACK because QString rounds up. Eg QString::number(0.999*100.0, 'f' ,1) == 99.9
** but QString::number(0.9999*100.0, 'f' ,1) == 100.0 The problem manifests when
** the number has more digits after the decimal than we want AND the digit after
** our 'wanted' is >= 5. In this case our last digit gets rounded up. So for each
** precision we add an extra 0 behind 1 in the below algorithm.
** However this, approach has a drawback. eg (99,99, 2) returns 99.98 and (99.99, 3)
** returns 99.989. This is a minor issue because mostly we want to use precision 1 or 2
** and the double fed into this function will have more decimal places than required
** precision anyway.*/
double prec = std::pow(10.0, precision);
return QLocale::system().toString((int)(n*(int)prec)/prec, 'f', precision);
}