100. Convert a String to Float

Back To All Submissions
Previous Submission
Next Submission

Code

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

float custom_atof(const char *str) {
    int index = 0;
    float result = 0.0f;
    float divider = 0.1f;
    int sign = 1;
    int terminated = 0;
    int has_dot = 0;
    const char offset = '0';

    // check optional sign at beginning
    if (str[0] == '+') {
        // + at beginning -> number is positive (default)
        index++;
    }
    if (str[0] == '-') {
        // - at beginning -> number is negative
        sign = -1;
        index++;
    }

    // read digits in string
    while ((str[index] != '\0') && !terminated) {
        char ch = str[index];
        if (ch >= '0' && ch <= '9') {
            // we have a digit
            if (has_dot) {
                result += (ch - offset) * divider;
                divider /= 10;
            } else {
                result = result * 10 + (ch - offset); 
            }
        } else if (ch == '.') {
            // we have a decimal point
            if (has_dot) {
                // this is the second dot -> illegal
                terminated = 1;
            }
            has_dot = 1;
        } else {
            // we have something else -> illegal
            terminated = 1;
        }
        index++;
    }

    return result * sign;
}

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

 

 

 

Was this helpful?
Upvote
Downvote