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
    bool is_neg = false;
    float f = 0;
    int count=0;
    while(*str != '\0')
    {
        if( count == 0)
        {
            if(*str == '-') 
            {
                 is_neg = true;
            str++;
            }
            else if(*str == '+')
            {
                is_neg = false;
            str++;
            }
            count++;

        }
        if(*str == '.')
        {
            count++;
        }
        else
        {
            f = f * 10 + (*str - '0');
            if(count >= 2)
            {
                count++;
            }
        }
        str++;
    }
    for(int i = 2;i<count;i++)
    {
        f =f/10;
    }
    if(is_neg == true)
    {
        f *= -1;
    }
    return f;;
    
}

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