How to convert float to string in C

5 Answers

0 votes
#include <stdio.h> 
#include <stdlib.h> 
      
int main() 
{ 
    float f = 376.287152;
    char arr[32]; 
   
    gcvt(f, 10, arr); 
   
    printf("%s\n", arr); 
        
    return 0; 
} 
      
      
      
/*
run:
      
376.2871399
    
*/

 



answered Aug 25, 2019 by avibootz
edited Oct 30, 2024 by avibootz
0 votes
#include <stdio.h> 
#include <stdlib.h> 
      
int main() 
{ 
    float f = 376.287152;
    char arr[32]; 
   
    sprintf(arr, "%g", f);
   
    printf("%s\n", arr); 
        
    return 0; 
} 
      
      
      
/*
run:
      
376.287
    
*/

 



answered Aug 25, 2019 by avibootz
edited Oct 30, 2024 by avibootz
0 votes
#include <stdio.h> 
#include <stdlib.h> 
      
int main() 
{ 
    float f = 376.287152;
    char buf[32];
    int len = snprintf(buf, 32, "%f", f);
    char *arr = (char *)malloc(len + 1);
 
    snprintf(arr, len + 1, "%f", f);
 
    printf("%s\n", arr); 
     
    free(arr);
        
    return 0; 
} 
      
      
      
/*
run:
      
376.287140

*/

 



answered Aug 25, 2019 by avibootz
edited Oct 30, 2024 by avibootz
0 votes
#include <stdio.h> 
#include <stdlib.h> 
       
int main() 
{ 
    float f = 376.287152;
    char arr[32]; 
    
    sprintf(arr, "%e", f);
    
    printf("%s\n", arr); 
         
    return 0; 
} 
       
       
       
/*
run:
       
3.762871e+02
     
*/

 



answered Aug 25, 2019 by avibootz
edited Oct 30, 2024 by avibootz
0 votes
#include <stdio.h> 
 
int main() 
{ 
    float f = 123.456789;
    char arr[32];
     
    snprintf(arr, sizeof(arr), "%.6f", f);
     
    puts(arr);
     
    return 0; 
}   
        
  
        
/*
run:
        
123.456787
     
*/

 



answered Aug 28, 2019 by avibootz
edited Oct 30, 2024 by avibootz

Related questions

1 answer 226 views
1 answer 325 views
1 answer 251 views
2 answers 360 views
360 views asked Jan 13, 2019 by avibootz
1 answer 339 views
4 answers 599 views
599 views asked Nov 17, 2015 by avibootz
...