Convert a String to Float

Code

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

int power(int num, int exp){
    int result = 1;
    for(int i = 0; i < exp; i++){
        result*= num;
    }
    return result;
}

float custom_atof(const char *str) {
    // Your logic here
    float result = 0.f;
    int i = 0;
    int sign = 1;
    if(str[i]=='+'){
        i++;
    }
    if(str[i]=='-'){
        i++;
        sign = -1;
    }
    while(str[i]!='\0'){
        if(str[i]=='.'){
            i++;
            int decimal_place = 1;
            while(str[i]!='\0'){
                result += (float)(str[i]-'0') / (float)power(10, decimal_place);
                decimal_place++;
                i++;
            }
            return sign * result;
        }
        result = result * 10.f + (str[i]-'0');
        i++;
    }
    return sign * result;
}

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