How to convert string to double without changing actual data

Hi,I have to convert string to double. i'm using "atof" function to achieve same.

I have string as "0.0409434228722337" and i'm converting with "atof"

But i'm getting double value as "0.040943422872233702".
Why it adds 02 additionally at the end?

More example :
"0.0409434228722337" converts to "0.040943422872233702"
"0.067187778121134" converts to "0.067187778121133995"

Is there any other possibility to convert string to double without changing data ?

Perhaps if you took the time to investigate how floating point numbers are stored internally you might better understand what's involved.
http://en.wikipedia.org/wiki/Floating_point#Internal_representation
stringstream is another way of converting strings to numbers and vice versa.
Why it adds 02 additionally at the end?

Well, the article kbw pointed you at gives all the gory details, but the answer in a nutshell is because that's the closest it can get.

Remember, computers use base 2 not base 10. So it stores the fraction using binary, too. So rather than storing 0/10 + 4/100 + 0/1000 + 9/10000 + ... it's storing a/2 + b/4 + c/4 + ... where a, b, c are all either 0 or 1. As only a limited number of places are stored, it's not always possible to represent decimal fractions totally accurately.

As you did as the computer to store "0.040943422872233700" (it would have but zeroes in the space space).

For example: (using http://www.easysurf.cc/fracton2.htm )

0.5 decimal = 0.1 binary
0.2 decimal = 0.001100110011...

So 0.5 can be stored accurately, but not 0.2.

Andy
Last edited on
Hi all,

Thanks for reply. Andy , that means can we get exact result on convertion ?
No, it means you cannot always get an exact result.

Andy
Topic archived. No new replies allowed.