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
    float result = .0f;
    int pow10 = 10;
    float sign = 1.0f;

    bool point = 0;
    
    while (*str) {
        if (*str == '+') sign = 1.0f;
        else if (*str == '-') sign = -1.0f;
        else if (*str == '.') point = 1; 
        else if (!point) result = 10 * result + (*str - '0');
        else if (point) {
            result = result + (1.0f * (*str - '0') / pow10);
            pow10 *= 10;
        }
        str++;
    }


    return sign * 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