Convert a String to Float

Code

#include <stdio.h>
#include <stdint.h>
#include <math.h>
float custom_atof(const char *str) {
    // Your logic here
    float sgn = 1.0;
    float x = 0.0, y = 0.0;
    switch(*str){
        case('-'):
            sgn = -1.0;
        case('+'):
            str++;
    }
    for(;*str != '\0' && *str != '.'; str++){
        x = x * 10 + *str - '0';
    }
    if(*str == '.') str++;
    int power_minus_ten = 0;
    for(;*str != '\0'; str++){
    y = y * 10 + *str - '0';
    power_minus_ten++;
    }
    for(int i = 0; i<power_minus_ten;i++)
        y = y/10.0;
    x += y;
    x *= sgn;
    return x;
}

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