How to convert string to float?

abubacker picture abubacker · Oct 31, 2011 · Viewed 208.3k times · Source
#include<stdio.h>
#include<string.h>

int main() 
{
    char s[100] ="4.0800" ; 

    printf("float value : %4.8f\n" ,(float) atoll(s)); 
    return 0; 
}

I expect the output should be 4.08000000 whereas I got only 4.00000000.

Is there any way to get the numbers after the dot?

Answer

Mysticial picture Mysticial · Oct 31, 2011

Use atof() or strtof()* instead:

printf("float value : %4.8f\n" ,atof(s)); 
printf("float value : %4.8f\n" ,strtof(s, NULL)); 

http://www.cplusplus.com/reference/clibrary/cstdlib/atof/
http://www.cplusplus.com/reference/cstdlib/strtof/

  • atoll() is meant for integers.
  • atof()/strtof() is for floats.

The reason why you only get 4.00 with atoll() is because it stops parsing when it finds the first non-digit.

*Note that strtof() requires C99 or C++11.