tags:

views:

153

answers:

5

Hi,How to convert string (22.123) format number into float variable format without using any API in c++. This is just to understand more about the inside coding.. thnx

A: 

go over the number digit by digit by using a bunch of multiplications and divisions by powers of 10 and construct the string character by character.

shoosh
While this naive approach will of course work fine in most cases, there will be a significant precision loss. You won't be able to roundtrip float->string->float if you implement the latter conversion this way.
avakar
I was unaware that there is significantly different way of doing this. Where is your answer which explains it?
shoosh
+1  A: 
KennyTM
+3  A: 

something like:

double string_to_double(std::string s)
{
    int p = 0;
    int p_dec = s.length();

    double val = 0;

    for (int i=0; i<s.length(); ++i)
    {
        double digit = (double)(s[i] - '0');
        if (s[i] == '.') { p_dec = p; }
        else { val += digit*powf(10,p--); }
    }

    val /= powf(10, p_dec);
}
Inverse
You probably meant `pow`, not `powf`.
avakar
And you could extend that to deal with an optional '-' first. A possible 'e???' thereafter could be read using integral math; the resultant power can be subtracted from p_dec before use (though it might be easier to read if you change it's sign).
Eamon Nerbonne
And of course, in practice some sanity checking for the input is advisable, though not needed for an illustrative example.
Eamon Nerbonne
A: 

If you just want an idea of how to do it, the other answer, if you want an accurate result, the problem is not so simple and you should refer to the literature on the subject. An example: ftp://ftp.ccs.neu.edu/pub/people/will/howtoread.ps

AProgrammer
A: 

I'm pretty sure that the Plauger Standard C Library book has a disc with the source of strtod. http://www.amazon.co.uk/Standard-C-Library-P-J-Plauger/dp/0131315099

and there are online versions too: http://www.google.co.uk/search?hl=en&amp;client=firefox-a&amp;hs=IvI&amp;rls=org.mozilla%3Aen-GB%3Aofficial&amp;q=strtod+source+code

lilburne