Convert a String to Float

Code

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

float convert_arr(char *s,char *e){
    float num = 0;
    while(s<=e){
        num = num *10 + (*s - '0');
        s++;
    }
    return num;
}

float custom_atof(char *str) {
    float res = 0;

    int flag = 1;
    if(*str == '-'){
        flag = -1;
        str++;
    }else if(*str == '+'){
        flag = 1;
        str++;
    }

    char *start = str;
    char *end;

    while(*str){
        if(*(str+1) == '.' || *(str+1)=='\0'){
            end = str;
            res = convert_arr(start,end);
            start = str+2;
            break;
        }
        str++;
    }

    int i = 1;
    while(*start){
        res = res + ((float)(*start - '0')/(i*10));
        i = i*10;
        start++;
    }

    return flag * res;
}

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