# Thread: Convert string to float

1. ## Convert string to float

If not use atof, how can I complete the following function which can convert string to float?? Thanks..

Code:
```#include <stdio.h>
#include <ctype.h>
#include <math.h>

float strToFloat(const char s[]) {

}

int main() {
printf("%f\n", strToFloat("1"));
printf("%f\n", strToFloat("   1.23"));
printf("%f\n", strToFloat("-1.23"));
printf("%f\n", strToFloat("1.23456"));
printf("%f\n", strToFloat("0.00000001"));
printf("%f\n", strToFloat("0.0.1"));
printf("%f\n", strToFloat("1E2"));
printf("%f\n", strToFloat("0.0.1"));
printf("%f\n", strToFloat("1.23456E2"));
printf("%f\n", strToFloat("1.23456e3"));
printf("%f\n", strToFloat("2E"));
}```

2. Probably the easyest way to do this is to use sscanf().
Code:
```float fl;

sscanf(s, "%f", &fl);

return fl;```

3. Thank you.
But I can't use sscanf for the question. Is there any other function that I can use?

4. You could just write necessary logic to convert the strings to floats yourself.

If you haven't done anything of this sort before, try your hand at making a basic ASCII to Integer function first. Once you can do this, you should be a lot closer to turning a string into a float.

5. strtod() is part of the standard library, otherwise you'll have to sscanf it yourself

6. Yep, yep - you could look at strtod. I generally use it for floating point input, and strtol for integer input. Have a look at this for an idea of how to implement your code. Of course the linked page deals with strtol, but after reading your documentation for both strtol and strtod, it is fairly trivial to use strtod in place of strtol for your needs.

7. Do this using side-by-side development, i.e. check that your code gives the same answer as sscanf.
Other than that, just approach this one character at a time. Look at the first character, and adjust the value of your float or other member variables accordingly, then move on to the next character. You'll need something to track the sign of the number, and whether you've seen the sign yet, and something to track whether you've seen the decimal point yet, etc.