Search code examples
c++qtqstringqtcore

Qt/C++ Convert QString to Decimal


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

Solution

  • 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