Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[Solved] Modulo operator %



  • Hi

    Following sample from standard C:
    where for instance a = 1234 (value) and b = 10000000 (scaling factor)
    printf("value: %d.%6.6d\n", ( a / b ), ( a % b ));
    would return: value: 0.001234

    I now tried to do something similar in Qt:

    ui->Label->setText(tr("value: %1.%2")
    .arg(data.section(' ', 7, 7).toUInt(&ok, 10) / data.section(' ', 8, 8).toUInt(&ok, 10))
    .arg(data.section(' ', 7, 7).toUInt(&ok, 10) % data.section(' ', 8, 8).toUInt(&ok, 10), 7));
    

    which leads me to
    value: 0. 1234
    and I can not manage to have it filled with '0' instead of ' '.

    What am I doing wrong?
    Thanks



  • @McLion
    One way I can think off is using the QTextStream::setPadChar. You have to write to a string there.
    Personally I would prefer using std::ostringstream, but basically do the same.


  • Moderators

    I might be missing something but why not just do this?

    QString::number((double)a/b, 'f', 6);
    

    Btw. 1234/10000000 is 0.0001234 not 0.001234 so your padding in the first example is flawed.



  • Thank you guys.
    I got it solved. I extended the .arg() with the padding which in the first place did not work because I forgot the QChar casting. Here's how it works:

    ui->label->setText(tr("BER: %1.%2")
    .arg(data.section(' ', 7, 7).toUInt(&ok, 10) / data.section(' ', 8, 8).toUInt(&ok, 10))
    .arg(data.section(' ', 7, 7).toUInt(&ok, 10) % data.section(' ', 8, 8).toUInt(&ok, 10), 6, 10, QChar('0')));
    

    @Chris-Kawa:
    You're right. 6 is correct ... typo.

    btw: I still could not figure how to mark as code in the new forum ..


  • Moderators

    @McLion To post code surround it with backticks i.e. ```your code here``` for a code block or `your code` for inline code.



  • Thanks.
    I tried with the forward and the straight tick but missed to try with the backward.


Log in to reply