c++ - Qt/C++ 将QString转为十进制

标签 c++ qt qstring qtcore

如何将 QString 转换为十进制数?

在 C# 代码中它看起来像这样:

public static decimal ConvertToDecimal(string tekst, bool upperOnly)
{
decimal num = 0m;
decimal num2 = 1m;
string text = upperOnly ? "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" : "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234";
int i = tekst.Length - 1;
while (i >= 0)
{
    num += text.IndexOf(tekst[i]) * num2;
    i--;
    num2 *= text.Length;
}
return num;
}

最佳答案

根据 documentation :

int QString::toInt(bool * ok = 0, int base = 10) const

Returns the string converted to an int using base base, which is 10 by default and must be between 2 and 36, or 0. Returns 0 if the conversion fails.

If a conversion error occurs, *ok is set to false; otherwise *ok is set to true.

If base is 0, the C language convention is used: If the string begins with "0x", base 16 is used; if the string begins with "0", base 8 is used; otherwise, base 10 is used.

The string conversion will always happen in the 'C' locale. For locale dependent conversion use QLocale::toInt()

Example:

QString str = "FF";
bool ok;
int hex = str.toInt(&ok, 16);       // hex == 255, ok == true
int dec = str.toInt(&ok, 10);       // dec == 0, ok == false

请注意,根据您的具体用例,您可能还希望查看以下文档:

long QString::toLong(bool * ok = 0, int base = 10) const

qlonglong QString::toLongLong(bool * ok = 0, int base = 10) const

double QString::toDouble(bool * ok = 0) const

float QString::toFloat(bool * ok = 0) const

关于c++ - Qt/C++ 将QString转为十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20729239/

相关文章:

c++ - 如何使用VS编译器将预处理文件编译成目标文件

c++ - 使用 C++ 模板参数作为另一个模板的参数?

c++ - 跨平台 Qt 应用程序中的全局热键

将 QString 转换为 GB

c++ - 在类中包含对象还是更好地从该类派生?

c++ - TDD 让我除以零。可以吗?

qt - 从 uchar[] 平台创建的 QImage 的字节顺序是否依赖于平台?

c++ - QT - 指向全局内存的指针

c++ - Qt QString toInt() 失败

c++ - QList<QString> 运算符<<