[Qt-creator] tofloat() function gives inappropriate results

Andre Poenitz andre.poenitz at mathematik.tu-chemnitz.de
Sat Jul 10 15:37:41 CEST 2010


On Sat, Jul 10, 2010 at 04:28:23PM +0530, 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. 

This has nothing to do with Qt Creator, not even wit Qt and only
marginally with C++, it's just the way floating point numbers work.
  
> For example : If the string value is 7.6 then the output of function
> to float is 7.5999...

The value 7.6 has no finite representation in base 2. It's something
like 111.1001100110011... with the 0011 part repeating infinitely.

Whenever you try to store that form in some finite memory it needs to be
rounded or cut off at some point. So the value stored is _not_ 7.6 but
something close to it, and there is no way to reconstruct the original
value, as the cut-off part is permanently lost.

There are several approaches to avoid this "loss" (like using fixed
point arithmetic, rounding, or not converting to floating point at all).

Andre'



More information about the Qt-creator-old mailing list