Convert a String to Float

Code

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

float custom_atof(const char *str) {
    // Your logic here
    int len;
    for(len=0;str[len]!='\0';len++);

   
    float sum =0;
    int mul = 10;
    int i=0;
        if(str[i] == '+' || str[i] == '-') i++;
        while(str[i] != '.' && (i < len) && str[i] ){
        
            sum *= 10;
            char temp;
            temp = str[i] - '0';
            sum += temp;
            i++;
        }
        //printf("%f\n",sum);
         if(str[i] == '.') i++;
         while(i<len){
       
        float temp=0;
        
        temp = (float)str[i] - '0';
        temp = temp/mul;
        //printf("%f\n",temp);
        sum += temp;
        
        mul *= 10;
        i++;
    }

    if(str[0] == '-') {
        float temp=0;
        temp = sum;
        sum *= 2;
        sum = temp - sum;
    }
    
    return sum;
}

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