Reputation: 1269
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 ?
Upvotes: 4
Views: 8484
Reputation: 3132
The numbers 49.5 and 50.5 are represented exactly in IEEE floating point.
But the IEEE floating-point standard supports various algorithms for rounding. Unless you take explicit steps to control which rounding algorithm is used, you will get whatever algorithm your environment chose as the default.
Specifically, it looks like your environment is using banker's rounding. When a number is exactly midway between two possible results, banker's rounding rounds it so that the last digit is even.
So 49.5 rounds to 50. And 50.5 also rounds to 50.
Also see this answer: Qt: Roundoff of 12.625 by 2 returns 12.62
Upvotes: 1
Reputation: 4186
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.
double value = 0.3;
int result = static_cast<int> (value * 1000);
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.
Upvotes: 7
Reputation: 7173
Output is correct. Read manuals, for example, QString Class Reference, and Argument Formats.
You just output, but not modify. If you want get int
numbers, add 0.5 add cast to int
, like:
...
int toInt(float x)
{
return int(x+0.5);
}
...
qDebug()<<toInt(50.5);
qDebug()<<toInt(49.5);
Upvotes: 0