-1

how do i get/convert the text from a QLineEdit field. the code below is operated by a button / slot.

but when compiled and pressing the button, 0.00000000000 shows up. no calculation takes place, whatever numbers i type into fields.

float solution = 0.0;

QString value_A = ui->doubleSpinBox_1->text();
float floatvalue_A = value_A.toFloat();
QString value_B = ui->lineEdit_1->text();
float floatvalue_B = value_B .toFloat();

if(floatvalue_A == 0.0){
    QMessageBox::information(this, "empty","",QMessageBox::Ok);
}

solution = (floatvalue_A * floatvalue_B);
ui->lineEdit_result_1->setText(QString::number(solution, 'f', 10));

the code editor indicates:

ui->lineEdit_result_1->setText(QString::number(solution, 'f', 10)); warning: implicit conversion increases floating-point precision: 'float' to 'double'

here also:

if(floatvalue_A == 0.0){ warning: implicit conversion increases floating-point precision: 'float' to 'double'
    QMessageBox::information(this, "empty","",QMessageBox::Ok);
}

what am i doing wrong? i used the QMessageBox to find out where the code is going wrong, no values are retrieved from the form fields.

NaturalDemon
  • 934
  • 1
  • 9
  • 21

3 Answers3

2

I just run this code in a MainWindow and it works as expected

  connect(ui->pushButton, &QPushButton::clicked, this, [&]() {
        auto f1 = ui->lineEdit->text().toFloat();
        auto f2 = ui->lineEdit_2->text().toFloat();
        auto f3 = ui->doubleSpinBox->value();
        auto sum = f1 + f2 + f3;
        ui->lineEdit_3->setText(QString::number(sum));
  });
F.Guerinoni
  • 277
  • 2
  • 12
0

I believe the first warning comes from the fact that QString::number doesn't have an overload for float, so the "solution" variable is getting promoted to a double. You can cast it explicitly to get rid of the warning:

QString::number ((double) solution, 'f', 10)

Alternately, you could declare "solution" as a double and simply work with double values throughout.

The second statement generates a conversion warning because "0.0" is a double which then forces floatvalue_A to promote to a double. There's a discussion about the implied type of 0 here:

C++ difference between 0 and 0.0

If you stay with floats in your code, you can use "0.0f" to force the constant to be a float rather than a double, and that should get rid of the warning. If you switch your variables to double throughout, then it will automatically go away.

goug
  • 2,294
  • 1
  • 11
  • 15
0

you are comparing double against a float, and that cause a precision lost, that is the reason why.

0.0 is a literal double until you don explicity tell qt you want a float

like doing

auto myFloat{0.0f};

aside note: you shouldnt do comparations like this:

 floatvalue_A == 0.0
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97