PDA

View Full Version : How to convert QString to float and compare values?



Gokulnathvc
31st January 2013, 10:21
I would like to convert QString values to float and then compare them..

I have used toFloat(), toDouble() , but it is not working.


QString version1 = "2.02.01";
QString version 2 = "2.02.02"
if(version1.toFloat() < version2.toFloat()) // just 2 is returned everytime.
{

}


How to resolve it???

wysota
31st January 2013, 10:26
A floating point number can have only one decimal point. These have two thus they are not valid floating point numbers.

Gokulnathvc
31st January 2013, 10:36
Could you explain how to compare those two values?
QString version1 = "2.02.01";
QString version 2 = "2.02.02"

Santosh Reddy
31st January 2013, 13:47
There are couple of ways

1. Compare the string directly, character by character
or
2. Split into substrings, then convert eash substring to integer, then compare the integers.
or
3. Write a special function to convert into comparable numbers (weights)
or
4. Just remove the delimiters, then convert to integers, then compare
Example


QString version1 = "2.02.01";
QString version2 = "2.02.02";

while(version1.contains("."))
version1 = version1.remove(QString("."));

while(version2.contains("."))
version2 = version2.remove(QString("."));

if(version1.toUInt() < version2.toUInt())
{
...
}

or
5. Maintain a map table to compare
Example


QString version1 = "2.02.01";
QString version2 = "2.02.02";

QMap<int, QString> map;
map.insert(1, "2.02.01");
map.insert(2, "2.02.02");
if(map.key(version1) < map.key(version2))
{
....
}

Lesiok
31st January 2013, 14:22
If the strings are always compared to that format you can use this function :

int ver2int( QString const &ver )
{
QStringList m_list = ver.split('.');
int ret_val = 0;

for( int i = 0; i < m_list.size(); i++ )
ret_val = 100*ret_val + m_list.at(i).toInt();

return ver2int;
}

QString version1 = "2.02.01";
QString version2 = "2.02.02";

if(ver2int(version1) < ver2int(version2))
{
....
}


Not tested, it should work.

Santosh Reddy
31st January 2013, 14:51
Lesiok's example is what I ment in my 3rd bullet, there you go one more example

ChrisW67
1st February 2013, 08:32
If they are always in exactly that format, i.e. "n.nn.nn" where n is a digit, then a straight string comparison for less-than, greater-than or equal-to comparison should work.