Truncating float numbers while displaying in Label field

  • 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().


  • Moderators

  • 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"

  • 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>).

  • @VRonin

    I am mistaken about parseFloat, as you pointed out.
    modified code as you told, it is working now.

    Thank you.

  • @Toniy
    Thank you,

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.