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) {
    bool isNegative = false;
    
    if(*str == '-'){
        isNegative = true;
        str++;
    }
    else if(*str == '+'){
        str++;
    }

    float result = 0;
    float base_a = 10;
    float base_b = 1;

    while(*str != '\0'){
        if(*str == '.'){
            base_a = 1;
            base_b = 0.1;
            str++;
            continue;
        }
        result = ((result * base_a) + (*str - '0') * base_b);
        if(base_a == 1){
            base_b *= 0.1;
        }
        str++;
    }
    if(isNegative){
        result = 0 - result;
    }
    return result;
}

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