0

In my project I have to read some numeric data form an xml file ,use it ,and save it on disk in an another directory.

Skipping the file paring it comes to the problem of std::string to float conversion:

std::string sFloatNumber;
float fNumber = std::atof(sFloatNumber);

Which works fine but I noticed small deviations between value written in std::string and the one recieved after conversion to float (about ~0.0001).

Deviation is small but after number of such operations can accumulate to a big inacurracy later on.

So I ask if there is some conversion between std::string and float that has 1:1 accuracy?

Amadeusz
  • 1,488
  • 14
  • 21
  • 1
    Maybe using a `double` gives you a better precision? – πάντα ῥεῖ Aug 14 '15 at 10:39
  • Can you specify what you mean with "1:1" accuracy? Not all decimal numbers can be exactly represented in binary floating point format. 9 places after the decimal point is enough to capture the full accuract of `float`. But the value cannot always be exact. 0.1 is not representable in binary, just like 1/3 is not representable in decimal, for example. – Angew is no longer proud of SO Aug 14 '15 at 10:40
  • Floating point numbers are by their very nature innacurate. – dandan78 Aug 14 '15 at 10:40
  • Thanks for your help. Now I see that I didn't ask the right question ;) – Amadeusz Aug 14 '15 at 10:57

1 Answers1

1

You can't really can't make the conversion more precise than what you'd achieve by using the inbuilt operators for this. The reason is that floats can't represent all numbers. What they can represent is the number closest to the one you input, and I guess that is what they are showing. So there is no way possible in which you can convert a string exactly into a float.

If you want more accuracy, I suggest you use double. However, that also has a limit on the accuracy, but much better than float nonetheless. The reason for this is that double uses 64 bits to represent a number, whereas a float uses 32 bits. But their method of storing a number is similar, and so the same restrictions apply.

therainmaker
  • 4,253
  • 1
  • 22
  • 41