Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Best way to format numbers in strings
Forum Updated to NodeBB v4.3 + New Features

Best way to format numbers in strings

Scheduled Pinned Locked Moved General and Desktop
3 Posts 3 Posters 4.7k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • B Offline
    B Offline
    BasicPoke
    wrote on last edited by
    #1

    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. :(
    Thanks
    Ron

    1 Reply Last reply
    0
    • C Offline
      C Offline
      clochydd
      wrote on last edited by
      #2

      Hi,
      isn't that simple enough?

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

      shows: 1 "01"
      @

      1 Reply Last reply
      0
      • X Offline
        X Offline
        Xander84
        wrote on last edited by
        #3

        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

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved