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) {
    float num = 0;
    float fraction = 0;
    float divisor = 10.0;
    int sign  = 1;
    int dot_seen = 0;

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

    while(*str) {
        if(*str >= '0' && *str <= '9') {
            if(dot_seen != 1) {
                num = num *10 + (*str - '0');
            } else {
                fraction += ((*str - '0') /divisor );
                divisor *= 10;
            }
            
        } else if(*str == '.') {
            dot_seen = 1;
        }
        str++;
    }
    return (num + fraction) *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