Qt中字符串与数值之间的转换

本文最后更新于:2022年6月10日 下午

QString 类从字符串转换为整数的函数有:

1
2
3
4
5
6
// base = 10, 表示十进制,默认什么都不输入就是十进制的
int toInt(bool* ok = Q_NULLPTR, int base = 10)
const long toLong(bool* ok = Q_NULLPTR, int base = 10)
const short toShort(bool* ok = Q_NULLPTR, int base = 10)
const uint toUInt(bool* ok = Q_NULLPTR, int base = 10)
const ulong toULong(bool* ok = Q_NULLPTR, int base = 10) const

QString 将字符串转换为浮点数的函数有:

1
2
double toDouble(bool* ok = Q_NULLPTR) const
float toFloat(bool* ok = Q_NULLPTR) const

希望显示两位小数,下面4行语句都可以实现这个功能:

1
2
3
4
str = QString::number(total, 'f', 2);
str = QString::asprintf("%.2f", total);
str = str.setNum(total, 'f', 2);
str = str.sprintf("%.2f", total);

QString 进制之间的相互转换

以2进制为例

  • QString 转 int

    1
    2
    3
    4
    QString str = "50";
    bool ok;
    int value = str.toInt(&ok);
    qDebug() << value; // 引入头文件 #include <QDebug>

    输出50

  • int 转 2进制 QString ,两种方式,任选其一

    • 第一种:

      1
      2
      3
      int value = 50;
      QString str = QString::number(value, 2); // 转换为2进制存入str中
      qDebug() << str;

      输出110010

    • 第二种:

      1
      2
      3
      4
      int value = 50;
      QString str;
      str = str.setNum(value, 2);
      qDebug() << str;

      输出110010



Qt中字符串与数值之间的转换
https://tian-sj.github.io/2022/05/12/Qt中字符串与数值之间的转换/
作者
田世纪
发布于
2022年5月12日
许可协议