PDA

View Full Version : Rounding in QT



TomASS
5th January 2012, 08:10
Wellcome all!

I'm writting the software for invoicing. Essential to this is to use mathematical rounding to two decimal places.

I've tried to use:

QString::number(value,'f',2).toDouble();
but - it doesne't work!

for example:
2582.3250 return me: 2582.32 -it's wrong! It should be 2582.33

what am I doing wrong?

wysota
5th January 2012, 11:27
You are falsely assuming any floating point number can be represented by the float datatype.

ChrisW67
5th January 2012, 22:09
The closest approximation of 2582.3250 as a float is 2582.324951171875. Perhaps it is obvious now why it rounds the way it does.
Have a play with this here (http://babbage.cs.qc.cuny.edu/IEEE-754/index.xhtml)

You are also assuming there is only one way to round (http://en.wikipedia.org/wiki/Rounding): that is 0.5 rounds up. The IEEE754 default rounding method is round-to-even so 1.125 rounds to 1.12, and 1.375 rounds to 1.38, and that is what Qt does also:


qDebug() << QString::number(1.125, 'f', 2); // outputs "1.12"
qDebug() << QString::number(1.375, 'f', 2); // outputs "1.38"

(Both those numbers have an exact floating point representation)