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 len = 0; int dot = 0;
    while(str[len] != '\0') { 
        if(str[len] == '.') dot = len;
        len++;
    }
    if(dot == 0) dot = len;

    int sign = 1, index = 0;
    if(str[index] == '-') {
        sign = -1;
        index++;
    } else if(str[index] == '+') index++;

    float result = 0.00; float mul = 1.00; int start = dot;
    // Integers
    while(start > index){
        result += (float)(str[start-1] - '0') * mul;
        mul *= 10;
        start--;
    }
    mul = 10.00; start = dot;
    while(start < len-1) {
        result += (float)(str[start+1] - '0') / mul;
        mul *= 10;
        start++;
    }

    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