Convert a String to Float

Code

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


float custom_atof(const char *str) {
    // Your logic here
    int index = 0;
    float number = 0.1;
    int decimal = 0;
    float temp = 0;

    while(str[index] != '\0')
    {
        if(str[index] == '.')
        {
            decimal = 1;
            index++;
            continue;
        }else if(str[index] == '+' || str[index] == '-')
        {
            index++;
            continue;
        }

        if(!decimal)
        {
            temp = temp*10 + str[index] - '0';
        }
        else
        {
            temp = temp + (str[index] - '0') * number;
            // number = str[index] - '0';
            // number = number
            // temp = temp / 10;
            number = number * 0.1 ;
        }
        index++;
    }
    if(str[0] == '-')
    {
        return temp * (-1);
    }
    return temp;
}

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