[Qt-interest] QString::number question

Marc Ferland marc at mferland.net
Wed May 26 20:39:41 CEST 2010


Hi,

I'm currently using the QString::number() function to convert real
values to strings.  More precisely I'm using the functio with these
arguments: QString::number(num, 'g', 4);

The result is a little surprising when the number is near 0. Here's a
little program that shows the problem I'm having:

#include <QString>
#include <QtGlobal>
#include <QtDebug>

int main()
{
   quint32 i;
   qreal step = 0.2;
   qreal start = -1.0;
   
   for (i = 0; i < 10; ++i)
   {
      qDebug() << "QString::number(start, 'g', 4)" << QString(QString::number(start, 'g', 4));
      qDebug() << "QString::number(start, 'f', 4)" << QString(QString::number(start, 'f', 4));
      start += step;
   }
}

The output is:
QString::number(start, 'g', 4) "-1" 
QString::number(start, 'f', 4) "-1.0000" 
QString::number(start, 'g', 4) "-0.8" 
QString::number(start, 'f', 4) "-0.8000" 
QString::number(start, 'g', 4) "-0.6" 
QString::number(start, 'f', 4) "-0.6000" 
QString::number(start, 'g', 4) "-0.4" 
QString::number(start, 'f', 4) "-0.4000" 
QString::number(start, 'g', 4) "-0.2" 
QString::number(start, 'f', 4) "-0.2000" 
QString::number(start, 'g', 4) "-5.551e-17" 
QString::number(start, 'f', 4) "-0.0000" 
QString::number(start, 'g', 4) "0.2" 
QString::number(start, 'f', 4) "0.2000" 
QString::number(start, 'g', 4) "0.4" 
QString::number(start, 'f', 4) "0.4000" 
QString::number(start, 'g', 4) "0.6" 
QString::number(start, 'f', 4) "0.6000" 
QString::number(start, 'g', 4) "0.8" 
QString::number(start, 'f', 4) "0.8000"

All the converted numbers seem ok, except for the 0 which shows as
"-0.000" or "-5.551e-17". Is there anyway to tell QString to just
round to the nearest value which makes sense (based on the precision
for example)?

Am I forced to use a small epsilon to detect when the value is near
zero?

Regards,

Marc

Note: Yes, I am aware of the problems of converting binary numbers to
decimal. I just think there should be a way to round based on the
precision provided.



More information about the Qt-interest-old mailing list