I am finding some thing weird in number(float) to string conversion..
Here is the sample code.
#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QString>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug()<<QString::number(50.5, 'f', 0);
qDebug()<<QString::number(49.5, 'f', 0);
return a.exec();
}
Here the output is
Starting /home/asit/qt/qstring1-build-desktop/qstring1...
"50"
"50"
The output should be 51 and 50. Can somebody tell what is the reason behind this output ?
The problem with floating point numbers is that they cannot be
represented exactly. So 49.5 might be stored as a number slightly more than 49.5. The same applies to 50.5, but this one might be stored as a number slightly less than 50.5.
This has bitten me before on Linux where you try and cast a
double to an int. Take e.g.
On e.g Solaris SPARC you will get 300 as you expect. With
gcc on Linux you get 299. Why? Well, although both
convert the double to an int by rounding down, on gcc on
Linux the double is assigned to a FPU 80 bit register
where it is represented by a number slightly less than
0.3. On Solaris (and in fact most other systems, including
VC++) the double is assigned to a 64 bit register
where it is represented as slightly bigger then 0.3.
If you want to be sure that you will have rounded your number to correct value, just add 0.5 before casting or use qRound() which will make that for you.