Truncating float numbers while displaying in Label field
-
wrote on 18 Apr 2017, 03:46 last edited by
i have to display float number with 2 digits after decimal point(truncate).
I have used
Label_Value->setText( QString::number(value, 'f', 2));it is rounding a larger value while displaying the value.
Then i used parseFloat()
value= parseFloat(value).toFixed(2);
Label_Value->setText( QString::number(value, 'f', 2));This is giving error message
'parseFloat' was not declared in this scope.
Searched in the net. didnot get any idea.
What is to added/declared to use parseFloat().Thanks.
-
i have to display float number with 2 digits after decimal point(truncate).
I have used
Label_Value->setText( QString::number(value, 'f', 2));it is rounding a larger value while displaying the value.
Then i used parseFloat()
value= parseFloat(value).toFixed(2);
Label_Value->setText( QString::number(value, 'f', 2));This is giving error message
'parseFloat' was not declared in this scope.
Searched in the net. didnot get any idea.
What is to added/declared to use parseFloat().Thanks.
@o6a6r9v1p said in Truncating float numbers while displaying in Label field:
parseFloat
What is parseFloat?
-
wrote on 18 Apr 2017, 06:09 last edited by Toniy
If you need floating value with certain precision without ceiling, try to get string longer by one symbol (three in your case) and remove all symbols that after second fractional digit:
// Let's consider three cases: // 1. value == 2.65796541324 (longer than two fractional symbols); // 2. value == 2.6 (shorter); // 3. value == 2 (integer). QString str(QString::number(value, 'f', 3)); // 1. str == "2.658"; 2. str == "2.600"; 3. str == "2.000" str.chop(str.length() - (str.indexOf('.') + 3)); // 1. str == "2.65"; 2. str == "2.60"; 3. str == "2.00" Label_Value->setText(str);
-
wrote on 18 Apr 2017, 06:52 last edited by VRonin
parseFloat
is Javascript, not C+++Label_Value->setText( QString::number(std::trunc(value*100.0)/100.0, 'f', 2));
will do the trick (remember to add#include <cmath>
). -
parseFloat
is Javascript, not C+++Label_Value->setText( QString::number(std::trunc(value*100.0)/100.0, 'f', 2));
will do the trick (remember to add#include <cmath>
). -
If you need floating value with certain precision without ceiling, try to get string longer by one symbol (three in your case) and remove all symbols that after second fractional digit:
// Let's consider three cases: // 1. value == 2.65796541324 (longer than two fractional symbols); // 2. value == 2.6 (shorter); // 3. value == 2 (integer). QString str(QString::number(value, 'f', 3)); // 1. str == "2.658"; 2. str == "2.600"; 3. str == "2.000" str.chop(str.length() - (str.indexOf('.') + 3)); // 1. str == "2.65"; 2. str == "2.60"; 3. str == "2.00" Label_Value->setText(str);
1/6