0

In a program, I want to display the number "0.12345" as ".12345" (removing the first zero) in a lineEdit. For this I wrote the simple code below:

QString s;
QTextStream ss(&s);

double temp = 0.12345;
int n = 0;

if(temp > 0)
{
    ss << ".";
    while (true)
    {
        temp *= 10;
        n = temp;
        if (temp == n)
            break;
    }
    ss << n;
}
lineEdit->setText(s);

When I run it, the program and Qt Creator hang and I need to rerun it to normally go out of it.

What is the problem that the program acts that way, please?

kefir500
  • 4,184
  • 6
  • 42
  • 48
Franky
  • 1,181
  • 2
  • 11
  • 33
  • I am confused is it the compiler itself, that _hangs_ (define _hang_), or your compiled code? Also, not related to your issue, but `n = temp; if(temp == n) break;` in a while loop will break out of your loop on the first iteration. – Algirdas Preidžius Jan 31 '17 at 19:36
  • I meant that the compiler suspends. since `n` is *int* and `temp` a *double* so in first iteration the loop does not finished. – Franky Jan 31 '17 at 20:10
  • oh, didn't notice the types of variables. Sorry. But you do realize, that, floating point numbers are only approximations, and may not be stored exactly as you write them? In addition: why such difficult parsing algorithm? What's wrong with `std::stringstream ss; ss << temp; std::string s = ss.str (); s.erase (s.begin());`? [Example](http://ideone.com/97eOGJ). – Algirdas Preidžius Jan 31 '17 at 20:27

1 Answers1

1

Problem

Your program never exits the while loop because you are comparing the floating point numbers using the == operator. This leads to miscalculation (you can read more about it here).

Solution

The proper way to check the double variables equality in Qt is to use the qFuzzyCompare function:

if (qFuzzyCompare(temp, n)) {
    break;
}

Simplification

If understand your task correctly, your code is too complicated for it. This should do the whole job:

double num = 0.12345;
if (num > 0 && num < 1) {
    QString str = QString::number(num).remove(0, 1);
    lineEdit->setText(str);
}
kefir500
  • 4,184
  • 6
  • 42
  • 48
  • Thank you very much. While your opinion (on using the operator *==* for *double* and *int*) is not right, but your *simplification*, especially **.remove** solved the issue. Thanks again. – Franky Jan 31 '17 at 21:01
  • @franky Glad to know that everything works fine now. Just of curiosity, why do you think that the advice to **not** compare floating point numbers using the `==` operator is wrong? This classic issue was widely discussed and described (e.g. [here](http://stackoverflow.com/questions/4682889/is-floating-point-ever-ok/4951103), [here](http://floating-point-gui.de/basic/), [here](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html)). – kefir500 Feb 01 '17 at 06:25