Convert a String to Float

Code

#include <stdio.h>
#include <stdint.h>
#include <math.h>

float custom_atof(const char *str) {
    int size=0;
    float res = 0.00;
    int i=0;
    int pos=-1;
    while(str[size]!='\0')
    {
        if((str[size]>='0'&&str[size]<='9')&&i==0)
        {
            float a = str[size] - '0';
            res = res*10 + a;
        }
        else if((str[size]>='0'&&str[size]<='9')&&i==1)
        {
            float a = (str[size]-'0')*pow(10,pos);
            res = res + a;
            pos--;
        }
        else if(str[size]=='.')
        {
            i = 1;
        }
        size++;
    }
    if(str[0]=='-')
    {
        return -res;
    }
    return res;
}

int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);

    // Remove newline
    uint8_t i = 0;
    while (str[i]) {
        if (str[i] == '\n') {
            str[i] = '\0';
            break;
        }
        i++;
    }

    float value = custom_atof(str);
    printf("%.2f", value);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

123.45

Expected Output

123.45