Convert a String to Float

Code

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

float custom_atof(const char *str) {
    float value = 0.0f;
    float sign = 1.0f;
    int i = 0;

    if (str[i] == '-') {
        sign = -1.0f;
        i++;
    }
    if (str[i] == '+') {
        sign = 1.0f;
        i++;
    }

    float whole = 0;
    for (;str[i] != '\0' && str[i] != '.'; i++) {
        if (str[i] >= '0' && str[i] <= '9') {
            whole = whole * 10.0f + (float)(str[i] - '0');
        }
    }

    if (str[i] == '\0') {
        return sign * whole;
    }
    i++;

    int digits = 0;
    float fraction = 0.0f;
    for (;str[i] != '\0'; i++) {
        if (str[i] >= '0' && str[i] <= '9') {
            fraction = fraction * 10.0f + (float)(str[i] - '0');
            digits++;
        }
    }

    while (digits > 0) {
        fraction = fraction / 10.0f;
        digits--;
    }

    return sign * (whole + fraction);
}

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