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 f=0;
    float frac = 0.1f;
    int sign = 1, dot_found =0;
    while(*str != '\0')
    {
        if(*str == '-')
        {
            sign = -1;
        }
        else if (*str == '.')
        {
            dot_found =1;
        }
        else if((*str>='0') && (*str<='9'))
        {
            if(dot_found)
            {
                f = f + (*str -'0')*frac;
                frac/=10;
            }
            else
            {
                f = f*10 + (*str - '0');
            }
            
        }
        str++;
    }
    return f*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