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
views:
153answers:
5
+3
Q:
How to convert string (22.123) format number into float variable format without using any API in c++
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
2010-03-10 07:24:00
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
2010-03-10 07:30:29
I was unaware that there is significantly different way of doing this. Where is your answer which explains it?
shoosh
2010-03-11 14:32:19
+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
2010-03-10 07:40:31
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
2010-03-10 07:51:06
And of course, in practice some sanity checking for the input is advisable, though not needed for an illustrative example.
Eamon Nerbonne
2010-03-10 07:52:38
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
2010-03-10 08:20:15
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&client=firefox-a&hs=IvI&rls=org.mozilla%3Aen-GB%3Aofficial&q=strtod+source+code
lilburne
2010-03-10 09:38:10