PDA

View Full Version : QDoubleSpinBox rounding



Talkless
7th January 2009, 12:10
Hello,

We have noticed anomalies in our applications accounting procedures where sale, cost prices are counted and etc. We are using Qt 4.3.5 on Windows.

Problem looks like is in QDoubleSpinBox double rounding. Please take a look:


#include <QApplication>
#include <QDebug>
#include <QDoubleSpinBox>
#include <QWidget>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);

QWidget w;

QDoubleSpinBox doubleBox(&w);
doubleBox.setDecimals(4);

doubleBox.setValue(2.79825);
qDebug() << QString::number(doubleBox.value(),'g');

doubleBox.setValue(2.79835);
qDebug() << QString::number(doubleBox.value(),'g');

w.show();

return a.exec();
}

You can notice that 2.79825 becomes 2.7982, and 2.79835 goes to, as I believe it really should, 2.7984.

I have no idea what kind of "double magic" is going on. Can it be Qt bug or "natural" double rounding behavior? You also can find similar strange behavior with 2.55, 2.555, 2.5555, 2.55555 and etc. with respectively 1, 2, 3, etc. decimal places - not always you will get "..6" at the end.

Thank you.

Lesiok
7th January 2009, 12:40
Generally double or float types are not good for money arithmetic because not all "money" values have binary represantation as double or float. The best solution is use special class for money arithmetic.
Remember : collection of real numbers is infinite. Collection of real numbers represented by double or float type is finite.