Qt / C ++将QString转换为Decimal

问题描述 投票:3回答:1

如何将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;
}
c++ qt qstring qtcore
1个回答
6
投票

根据documentation

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

返回使用基数转换为stringint,默认情况下为10,且必须介于2到36之间,或者为0.如果转换失败,则返回0。

如果发生转换错误,则*ok设置为false;否则*ok设置为true。

如果base为0,则使用C语言约定:如果字符串以“0x”开头,则使用base 16;如果string以“0”开头,则使用基数8;否则,使用基数10。

字符串转换将始终在“C”语言环境中进行。对于依赖于区域设置的转换,请使用QLocale::toInt()

例:

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

© www.soinside.com 2019 - 2024. All rights reserved.