⚠️ Forum Maintenance: Feb 6th, 8am - 14pm (UTC+2)

Best way to format numbers in strings

  • My broader question is that I need to learn how to format numbers in strings. My immediate concern is to format a char as a hex # using two characters, that is with a leading 0 if necessary. I have done a lot of searching and have not found an easy solution. I have seen QString::number and QString::arg but these seem very awkward. Is there anything as simple in Qt as printf? I know there is QString::sprintf but this is not recommend for use. I know I can add my own leading 0 if the result is only 1 char, but is that the only way?

    I just want my printf back. :(

  • Hi,
    isn't that simple enough?

    int i = 1;
    qDebug i << i << QString::number(i).rightJustified(2, '0');

    shows: 1 "01"

  • Why do you think QString::number and QString::arg is awkward? :D
    int i = 10;
    QString::number(i, 16).rightJustified(2, '0');
    QString("%1").arg(i, 2, 16, QLatin1Char('0'));
    both will output "0a"

    printf will be slower in most cases, because the string has to be parsed at run time, if you chain methods in c++ the compiler knows what you want to do so it should always be faster. At least I think that will happen, there may be compiler optimizations for printf, no clue :D

Log in to reply