Qt/C++ Convert QString to Decimal

ε祈祈猫儿з 提交于 2019-12-20 02:29:29

问题


How Can I convert QString to decimal ?

In C# code it look like that:

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;
}

回答1:


As per 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

Note that depending on your exact use case, you may wish to look into the following documentations as well:

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



来源:https://stackoverflow.com/questions/20729239/qt-c-convert-qstring-to-decimal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!