All submissions

Convert a String to Float

Code

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

float custom_atof(const char *str) {
    int sign = 1;
    float integer = 0, decimal = 0, divisor = 1;
    int dec_flg = 0;

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

    // Process digits
    while (*str) {
        if (*str == '.') {
            dec_flg = 1;
            str++;
            continue;
        }

        if (*str < '0' || *str > '9') {
            break; // Stop on non-digit (extra safety)
        }

        if (dec_flg) {
            decimal = decimal * 10 + (*str - '0');
            divisor *= 10;
        } else {
            integer = integer * 10 + (*str - '0');
        }

        str++;
    }

    return sign * (integer + decimal / divisor);
}

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

 

 

 

Loading...

Input

123.45

Expected Output

123.45