How to do the multiplication of small decimal numbers typed in QLineEdit?

Viewed 176

I am trying to calculate the forces between two charges(Coulomb's law) in c++ qt. I have 3 lineedits where the user can type numbers (the first lineedit is related to Point Charge 1(q1), the second lineedit is related to Point Charge 2(q2) and the third lineedit is related to the distance between two point charges(r)).As the user clicks on the push button, the answer(The force between two charges) appears in the label. When I type integer numbers or large decimal number (for example 0.25), the code works fine, but when I type very small decimal numbers such as 0.00000000000000000016, It returns 0. Is there a way to calculate such small numbers?

I would appreciate if someone could help me.

Here is my code:

void MainWindow::on_calculate1_clicked()
{


QString lineq1;
QString lineq2;
QString lineq3;
double lineq1num,lineq2num,lineq3num,J;

lineq1 = ui->lineEdit->text();
lineq2 = ui->lineEdit_2->text();
lineq3 = ui->lineEdit_3->text();

lineq1num = lineq1.toDouble();
lineq2num = lineq2.toDouble();
lineq3num = lineq3.toDouble();

//The coulomb's law
J = abs(lineq1num * lineq2num)/((4 * (3.14) * (8.85 * pow(10,-12)))*(lineq3num * lineq3num));

ui->label_4->setText(QString::number(J));

}

Here is the result I get, when typing small decimal numbers: The output

The formula I use is as follows: coulomb's law

The real answer is: answer

2 Answers

You should _NOT use the function abs, because that returns an integer, and as consecuense small decimal values will be rounded to Zero

use instead qFabs

here the doc:

qreal qFabs(qreal v)

Returns the absolute value of v as a qreal.

https://doc.qt.io/qt-5/qtmath.html#qFabs

It can be because the precision is set too low. Try setting it higher.

ui->label_4->setText(QString::number(J, 'g', 10));

The default precision when number() is called is 6. QString::number()

Related