Need help in exact conversion from string to double

Hi friends, I am facing a problem while conversion of string to double using different ways.

For example the string is: "148366.071110"
and after conversion to double using:

1. atof________: 148366.07110999999
2. sscanf______: 148366.00000431802
3. stringstream_: 148366.07110999999
4. strtod______: 148366.07110999999
Desired value_: 148366.07111000000
Last edited on
Well if built-in libraries are not helping you then there is no other option - you should do it manually !

You could iterate over the string starting from (n-1)th position to 0th then if it is not 'decimal point' then typecast that character to int and store it to variable , say n by formuale "n+=10^(ith digit)" . If you encounter '.' then store its position (say in variable x) and after loop divide the number by "10^x" .

NOTE:(1)you should use "long long int" for n,x.
(2)if "10^x" or "10^i" maybe too large then calculate the numbers after '.' and before it in two separate long long int .
(3)You may first remove trailing zeroes from string if you want little more effeciency

Here's the formal Algorithm :-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*Initializations -> 's' is string with number , 'n' is long long int in
 which to store value , 'x' is position of '.' in string
from left to right , 'i' is counter var. */

/*This is just algorithm , not code ,put little of your effort too ;) 
and do tell me if any further problem */

for (i=s.length()-1;i>=0;i--) {
  if (s.at(i)=='.') x=i; else {
    n+=10^((int)s.at(i))
  }
  n=n/(10^x)
}

//Now your number is in n ! 
Last edited on
Thanks Maggi for the suggestion .

I was thinking of same, but looking for some standard/windows library function which could help.
Look at this:

http://www.cplusplus.com/reference/iostream/ios_base/precision/

I checked it and it and with
double f = 148366.071110;
results the desired output
148366.071110 is not a valid value for the type double. That value lies between two valid values of the type double:

148366.07110999998985789716243743896484375, which is exactly 5097819386027683 * 2-35

and

148366.07111000001896172761917114257812500, which is exactly 5097819386027684 * 2-35

Your ideal value of 148366.071110 is a little closer to the first one, so when you attempt to store it in a double, the code that is compiled is actually storing 148366.07110999998985789716243743896484375.

There is no way around this, unless you switch to arbitrary precision floating-point library such as GNU MP. In most applications, it's sufficient to choose the right rounding for output so that it *looks* like 148366.071110.
Last edited on
Thanks every one...

coder777 will try it out.

Cubbi then it means that the double can handle only those fractional values for which exponent of 2 is full integral value.
Topic archived. No new replies allowed.