added atof
[fw/sdcc] / device / lib / _atof.c
1 /*  atof.c: converts an ASCII string to float
2
3     Copyright (C) 2003  Jesus Calvino-Fraga, jesusc@ieee.org 
4
5     This library is free software; you can redistribute it and/or
6     modify it under the terms of the GNU Lesser General Public
7     License as published by the Free Software Foundation; either
8     version 2.1 of the License, or (at your option) any later version.
9
10     This library is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13     Lesser General Public License for more details.
14
15     You should have received a copy of the GNU Lesser General Public
16     License along with this library; if not, write to the Free Software
17     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA */
18
19 #include <ctype.h>
20 #include <stdlib.h>
21
22 float atof(char * s)
23 {
24         float value, fraction;
25         char iexp;
26 #ifdef SDCC_mcs51
27         bit sign;
28 #else
29         char sign;
30 #endif
31
32         //Skip leading blanks
33         while (isspace(*s)) s++;
34
35         //Get the sign
36         if (*s == '-')
37         {
38                 sign=1;
39                 s++;
40         }
41         else
42         {
43                 sign=0;
44                 if (*s == '+') s++;
45         }
46
47         //Get the integer part
48         for (value=0.0; isdigit(*s); s++)
49         {
50                 value=10.0*value+(*s-'0');
51         }
52
53         //Get the fraction
54         if (*s=='.')
55         {
56                 s++;
57                 for (fraction=10.0; isdigit(*s); s++)
58                 {
59                         value+=(*s-'0')/fraction;
60                         fraction*=10.0;
61                 }
62         }
63
64         //Finally, the exponent (not very efficient, but enough for now*/
65         if (toupper(*s)=='E')
66         {
67                 s++;
68                 while(*s=='0') s++;//So atoi doesn't return an octal number
69                 iexp=(char)atoi(s);
70                 {
71                         while(iexp!=0)
72                         {
73                                 if(iexp<0)
74                                 {
75                                         value/=10.0;
76                                         iexp++;
77                                 }
78                                 else
79                                 {
80                                         value*=10.0;
81                                         iexp--;
82                                 }
83                         }
84                 }
85         }
86
87         if(sign) value*=-1.0;
88         return (value);
89 }