How to convert string to float in C

4 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>
  
int main(void)
{
    float f;
    char s[16] = "3.14";
   
    f = atof(s);
    printf("s = %s, f = %f\n", s, f);
    printf("s = %s, f = %.2f\n", s, f);

    return 0;
}


 
 
/*
run:
    
s = 3.14, f = 3.140000
s = 3.14, f = 3.14

*/

 



answered Nov 17, 2015 by avibootz
edited Jul 5, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
  
int main(void)
{
    float f;
    char s[16] = "3.14 result";
   
    f = atof(s);
    printf("s = %s, f = %f\n", s, f);
    printf("s = %s, f = %.2f\n", s, f);

    return 0;
}


 
 
/*
run:
    
s = 3.14 result, f = 3.140000
s = 3.14 result, f = 3.14

*/

 



answered Nov 17, 2015 by avibootz
edited Jul 5, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
  
int main(void)
{
    float f;
    char s[16] = "result 3.14";
   
    f = atof(s);
    printf("s = %s, f = %f\n", s, f);
    printf("s = %s, f = %.2f\n", s, f);

    return 0;
}


 
 
/*
run:
    
s = result 3.14, f = 0.000000
s = result 3.14, f = 0.00

*/

 



answered Nov 17, 2015 by avibootz
edited Jul 5, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
 
int main(void) {
    char s[] = "3.0700";
 
    float f1 = atof(s);
    float f2 = strtof(s, NULL);
 
    printf("%2.6f\n", f1);
    printf("%2.6f\n", f2);
}

 
 
 
/*
run:
 
3.070000
3.070000
 
*/

 



answered Jul 5, 2024 by avibootz

Related questions

1 answer 132 views
1 answer 198 views
1 answer 157 views
5 answers 633 views
633 views asked Aug 25, 2019 by avibootz
2 answers 235 views
235 views asked Jan 13, 2019 by avibootz
1 answer 228 views
...