Convert a String to Float

Code

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

float custom_atof(const char *str) {
    float val = 0;
    int i = 1;
    const char *ptr = str;

    if (*ptr == '-' || *ptr == '+')
        ptr++;

    // Parse integer part
    while (*ptr && *ptr != '.') {
        val = val * 10 + (*ptr - '0');
        ptr++;
    }

    // Parse fractional part only if '.' exists
    if (*ptr == '.') {
        ptr++;
        while (*ptr) {
            val += (*ptr - '0') / pow(10, i);
            ptr++;
            i++;
        }
    }

    if (*str == '-')
        val = -val;

    return val;
}

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