Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Weird problem with double and comparison operation



  • I have a function to check the sum of a table, it has worked so far as it is a very simple function, however I have a very weird issue where the variable soma end up with the value 100, but when comparing it to 100 it returns false.
    Here's my code:

        QDoubleSpinBox*  tempSpin;
        double soma = 0;
        for(int i = 0; i< ui->tableSecao->rowCount(); i++){
            tempSpin = qobject_cast<QDoubleSpinBox*>(ui->tableSecao->cellWidget(i, 2));
            soma+=tempSpin->value();
        }
        qDebug() << soma;
        qDebug() << (soma==100);
        if(soma<100){
            return 1;
        }else{
            return 0;
        }
    

    When I put 100 in one row and zeroes on the others, the return of the compatison is true, when I put the actual values, and the sum is exactly 100.00, the return is false.


  • Moderators

    @pedrogkb when you compare 2 doubles, or floats for that matter, chances are they are actually not equal

    Qt offers QFuzzyCompare for this exact reason
    https://doc.qt.io/qt-5/qtglobal.html#qFuzzyCompare

    You should read up about double /float in computer science.



  • Wow, thanks, I'm a Software Engineering student, i've studied floating point operations but never seem anything about this issue when comparing two values.


  • Lifetime Qt Champion

    @pedrogkb
    Hi
    I like this as friendly info about the issues with floating-point numbers in code.
    https://floating-point-gui.de/


Log in to reply