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 num=0;
    float decimal=0;
    uint8_t j=0;
    float inc=0.1;
    uint8_t flag =0;
    for(j; str[j]!= '\0';j++)
    {
        if(str[j]=='-' | str[j]=='+'  )
        {
            continue;
        }
        else if(flag==1)
        {  
                decimal= decimal + ((str[j] - '0') * inc);
                inc *= 0.1;

        }
        else if(str[j]=='.') 
        {
            flag=1;
            continue;
        }
        else
        {
            num=(num*10) + (str[j]-'0');
        }
    }   
           
    if(str[0]=='-')
    {
        return -(num+ decimal);
    }
    else 
    {
        return num+decimal;
    }
}

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