Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

How to implement the atof() function convert string to float in C

1 Answer

0 votes
#include <stdio.h>
#include <ctype.h>

double my_atof(char s[]);
  
int main(void)
{
    float f;
    char s1[30] = "3.14";
    char s2[30] = "72.9 result";
    char s3[30] = "-732.98";
    char s4[30] = "result = 3.14";
    char s5[30] = "       3.14";
   
    f = my_atof(s1);
    printf("s1 = %s, f = %f\n", s1, f);
    printf("s1 = %s, f = %.2f\n", s1, f);
    
    f = my_atof(s2);
    printf("s2 = %s, f = %f\n", s2, f);
    printf("s2 = %s, f = %.2f\n", s2, f);
    
    f = my_atof(s3);
    printf("s3 = %s, f = %f\n", s3, f);
    printf("s3 = %s, f = %.2f\n", s3, f);
    
    f = my_atof(s4);
    printf("s4 = %s, f = %f\n", s4, f);
    printf("s4 = %s, f = %.2f\n", s4, f);    
    
    f = my_atof(s5);
    printf("s5 = %s, f = %f\n", s5, f);
    printf("s5 = %s, f = %.2f\n", s5, f);

    return 0;
}
double my_atof(char s[]) 
{ 
    double d, after_point; 
    int i, sign; 
    
    for (i = 0; isspace(s[i]); i++);  
       
    sign = (s[i] == '-') ? -1 : 1; 
    
    if (s[i] == '+' || s[i] == '-') i++; 
       
    for (d = 0.0; isdigit(s[i]); i++) 
         d = 10.0 * d + (s[i] - '0'); 
           
    if (s[i] == '.') i++; 
       
    for (after_point = 1.0; isdigit(s[i]); i++) 
    { 
         d = 10.0 * d + (s[i] - '0'); 
         after_point *= 10; 
    } 
       
    return sign * d / after_point; 
} 


 
 
/*
run:
    
s1 = 3.14, f = 3.140000
s1 = 3.14, f = 3.14
s2 = 72.9 result, f = 72.900002
s2 = 72.9 result, f = 72.90
s3 = -732.98, f = -732.979980
s3 = -732.98, f = -732.98
s4 = result = 3.14, f = 0.000000
s4 = result = 3.14, f = 0.00
s5 =        3.14, f = 3.140000
s5 =        3.14, f = 3.14

*/

 



answered Nov 17, 2015 by avibootz

Related questions

1 answer 192 views
2 answers 266 views
1 answer 169 views
2 answers 149 views
1 answer 165 views
1 answer 113 views
...