How to convert a Qt string to a floating-point number?

In Qt, you can use the `toDouble()` function to convert a string to a floating-point number. Here is an example:

QString str = "3.14";

bool ok;

double number = str.toDouble(&ok);

if (ok) {

    qDebug() << "转换成功:" << number;

} else {

    qDebug() << "转换失败";

}

In this example, we are converting the string “3.14” to a floating point number. The `toDouble()` function returns the converted floating point number and informs if the conversion was successful through the reference parameter `ok`. If the conversion is successful, the value of `ok` is true, otherwise it is false.

It is important to note that if a string cannot be properly converted to a floating-point number, the `toDouble()` function will return 0.0 and set the value of `ok` to `false`. Therefore, it is recommended to check the value of `ok` before using the conversion result to ensure a successful conversion.

bannerAds