Convert a String to Float

Code

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

float custom_atof(const char *str) {
    // Your logic here
    float sign = 1;
    float whole_value = 0;
    float decimal_value = 0;
    int state = 0;
    float divisor = 10;

    if (*str == '+') {
        sign = 1;
        str++;
    } else if (*str == '-') {
        sign = -1;
        str++;
    }

    state = 1;
    while (1) {
        if (state == 1 && *str == '.') {
            state = 2;
        } else if (state == 1 && *str == 0) {
            break;
        } else if (state == 1) {
            whole_value = whole_value*10 + (*str - 48);
        } else if (state == 2 && *str == 0) {
            break;
        } else if (state == 2) {
            decimal_value += (*str - 48)/divisor;
            divisor *= 10;
        }
        str++;
    }

    return sign*(whole_value + decimal_value);
}

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