3

Can anybody explain this:

double nnn = 2678.87;
QVariant vvv(2678.87);
qDebug() << qRound(nnn*1000.0);    //--> 2678870
qDebug() << qRound(nnn*10000.0);   //--> 26788700
qDebug() << qRound(nnn*100000.0);  //--> 267887000
qDebug() << qRound(nnn*1000000.0); //--> 2147483647 !
qDebug() << qRound(vvv.toDouble()*1000000.0);  //--> -2147483648 !!!

The two last statements also have strange result in following format:

qDebug() << qRound(nnn*1000000); //--> 2147483647 !
qDebug() << qRound(vvv.toDouble()*1000000);  //--> -2147483648 !!!

I need to use last statement but it is wrong apparently!

Morteza M
  • 130
  • 6
  • Oops, didn't notice the negative sign on that last example. Might not be a duplicate after all. – Mark Ransom Jan 13 '23 at 14:03
  • But this is not a duplicate question!!!!!!!!!!!! – Morteza M Jan 13 '23 at 14:07
  • 3
    The desired value can't be represented as an `int`. Try [`qRound64`](https://doc.qt.io/qt-6/qtglobal.html#qRound64) instead. – G.M. Jan 13 '23 at 14:07
  • 1
    `qRound` returns an `int`, your value is larger than an `int`, try [`qround64`](https://doc.qt.io/qt-6/qtglobal.html#qRound64) instead (though you'll still eventually run into precision problems) – Alan Birtles Jan 13 '23 at 14:07
  • 1
    `qRound()` returns an `int`. It appears that, on your system, an `int` is 32 bits, and `nnn*1000000.0` produces a value that exceeds what a 32-bit `int` can represent. Either `qRound()` is deliberately catching the overflow and producing the maximum value an `int` can represent on your platform, or is falling back to what is allowed by C++ standards (IIRC, that is undefined behaviour, but I haven't checked if that has changed to unspecified or other behaviours in later standards). – Peter Jan 13 '23 at 14:07
  • OK. That's true. Please someone add this issue as an answer. I'll accept it. – Morteza M Jan 13 '23 at 14:13

1 Answers1

3

qRound returns an int, your value is larger than will fit in an int without overflowing. try qround64 instead.

Note you'll still eventually run into precision problems, a double can only exactly represent integers up to around 9 * 1015.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60