Convert a String to Float

Code

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

int is_digit(char c){
    return (c >= '0' && c<='9');
}

float custom_atof(const char *str) {
    // Your logic here
    float rez =0, fact =1;
    if(*str == '-'){
        str++;
        fact = -1;
    }
    
    for(int point_seen =0; *str; str++){
        if(*str == '.'){
            point_seen = 1;
            continue;
        }
        int d = *str - '0';
        if(d >= 0 && d<=9){
            if(point_seen) fact /= 10.0f;
            rez = rez * 10.0f + (float)d;
        }
    }

    return rez*fact;
}

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