Convert a String to Float

Code

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

float custom_atof(const char *str) {
    int f=0,re=0,i=0,s=1;
    float res=0,x=1;
    if(str[i]=='-'||str[i]=='+'){
    s=(str[i]=='-')?-1:1;
    i++;
    }
    for(i;str[i];i++){
        if(str[i]=='.'){
        f=1;
        continue;
        }
        if(!f){
            re=re*10+str[i]-'0';
        }
        else{
             x*=.1;
            res=res+(x*(str[i]-'0'));
        }
    }
   // printf("%d %f\n", re,res);
    float ans=s*(res+re);
    return ans;
}

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