Convert a String to Float

Code

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

float custom_atof(const char *str) {
    // Your logic here
    uint8_t read = 0;
    uint8_t dot = 0;
    int value1 = 0;
    int value_dot = 1;
    if(str[0] == '-' || str[0] == '+')
    {
        read = 1;
    }
    while((str[read] != '\0'&&(str[read]>=48 && str[read]<=57))|| str[read] == '.' )
    {
        if(str[read] != '.' )
        {
            value1 = value1*10 + ((int)str[read] - 48);
        }
        if(dot == 1)
        {
            value_dot = value_dot*10;
        }
        if(str[read] == '.')
        {
            dot = 1;
        }
        read++;
    }
    if(str[0] != '-')
    {
        return (float)value1/value_dot;
    }
    return (float)(-1)*(value1)/value_dot;
}

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