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 i=0, flag=0, value=0;
    float dec_pos = 1;
    int sign = 1;
    if(*(str + 0) == '-') {
        sign = -1;
        i++;
    }
    if(*(str + 0) == '+') {
        sign = 1;
        i++;
    }
    while(*(str + i) != '\0') {
        if(flag == 1) {
            dec_pos = dec_pos *10;
        }
        if(*(str + i) == '.') {
            flag = 1;
        }
        else {
            value = value *10 + (*(str + i) - '0');
        }

        i++;
    }
    // Your logic here
    return (value/dec_pos) * 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