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) {
    // Your logic here
    bool positive = true;
    char c = str[0];
    int idx = 0;
    if(c == '-') {
        positive = false;
        idx = 1;
    }
    else if( c == '+') {idx =1;}

    float result = 0.0f;
    
    while(str[idx] != '\0' && str[idx] != '.') {
        result = result * 10 + (str[idx] - 48);
        ++idx;
    }

    if(str[idx] == '.') {
        ++idx;
        float divisor = 10.0f;
        while(str[idx] != '\0') {
            result += (str[idx] - 48) / divisor;
            divisor *= 10;
            ++idx;
        }
    }

    return (positive) ? result : -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