Convert a String to Float

Code

#include <stdio.h>
#include <stdint.h>

float custom_atof(const char *str) {
    // Your logic here
    int sign=1;
    int index = 0;
    float val = 0;

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

    while((str[index]!='\0') && (str[index] != '.'))
    {
        val = val*10 + (str[index] - '0');
        index++;
    }
    if(str[index] == '\0')
    {
        return val*sign;
    }
    if(str[index] == '.')
    {
        index++;
    }

    float frac= 0.1;
    while((str[index]!='\0'))
    {
        val = val + (str[index] - '0')*frac;
        index++;
        frac = frac*0.1;
    }

    return val*sign;

    // return 0.0f;
}

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

 

 

 

Upvote
Downvote
Loading...

Input

123.45

Expected Output

123.45