Convert a String to Float

Code

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

float custom_atof(const char *s) {
    float reg=0.0f;
    float dau=1.0f;
    int i=0;
    if(s[i]=='+'){
        dau=1.0f;
        i++;
    }
    else if(s[i]=='-'){
        dau=-1.0f;
        i++;
    }
    while(s[i]>='0' && s[i]<='9'){
        reg=reg*10.0f+(s[i]-'0');
        i++;
    }
    float chia=10.0f;
    if(s[i]=='.'){
        i++;
        while(s[i]>='0' && s[i]<='9'){
      reg=reg+(s[i]-'0')/chia;
      chia=chia*10.0f;
      i++;
        }
    }

    return reg*dau;
}

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