Convert a String to Float

Code (Should have done with a more clean approach)

Maybe I should store only the significant numbers and store the decimal position (if any) in a variable and in last divide the final value by pow(10, decimal_pos) (something like that).

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

float custom_atof(const char *str) {
    // Your logic here
    int8_t sign = (*str == '-') ? -1 : 1;
    if (*str == '-' || *str == '+') str++;

    float value = 0;
    while (*str != '.' && *str != '\0') {
        value = value * 10 + (*str++ - '0');
    }
    str++;

    float pow = 0.1f;
    float after_dec = 0;
    while (*str != '\0') {
        // handle after decimal point
        after_dec = after_dec + ((*str++ - '0') * pow);
        pow /= 10;
    }

    return sign * (value + after_dec);
}

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