[Qt-creator] tofloat() function gives inappropriate results
David Dibben
dibben at ieee.org
Sat Jul 10 14:46:00 CEST 2010
Hi Ashish,
On 10/07/2010 19:58, Ashish Vats wrote:
> I am using QT4.5 , I want to convert the string value to float so I have
> used function tofloat(). But the results i am getting are not accurate.
> For example : If the string value is 7.6 then the output of function to
> float is 7.5999...
Firstly, I am think this might not be the right list for this question.
I would try Qt-Interest instead.
But to answer your question. The problem is not with QString::toFloat
but the nature of floating point numbers. A float cannot represent 7.6
exactly, so you will always get this type of error
For example, try this little program:
int main()
{
float x = 7.6f;
printf(" %16.15f \n", x);
double y = 7.6;
printf(" %16.15f \n", y);
reurn 0;
}
This does not use Qt's QString at all, and I get:
7.599999904632568
7.600000000000000
When using a float, you won't get 7.6. I would try using a double
instead. That will give a better representation, but there will still be
strings that do not get converted exactly. Depending on what you want to
do with the numbers that may or may not matter.
--
David Dibben
Web: http://www.daviddibben.com
Mail: dibben at ieee.org
More information about the Qt-creator-old
mailing list