Unsolved Proplem toDouble QString?
-
I have code:
QString number = "1.001"; double value = number.toDouble(); double value1 = 1; if(value - value1 < 0.001) { qDebug()<<"True"; }else { qDebug()<<"False"; }
I run and show log "True". I do not understand why this is so. Please help me!
-
Hi.
double
is a floating point number. It can not represent 0.001 exactly. It's more like 0.000999999999999889865875... -
@HAHAHAHAHA
This is not a problem with Qt. Using double always leads to precision errors.double value = 1.001; double value1 = 1.000; if (value - value1 < 0.001) { qDebug()<<"True"; }
This will print True
-
just in case you are wondering why this is like it is, here is a detailed explaination.
-
@raven-worx
Superb resource. You'd probably be surprised how many non-computer scientists and regular programmers haven't the slightest idea of those issues.@HAHAHAHAHA
If you wish to compare two floating points you could use Qt'sqFuzzyCompare
function orqFuzzyIsNull
to check if a floating point number is zero. -
I understand. Thank all =))