Convert a String to Float

Code

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

float custom_atof(const char *str) {
    // Your logic here
    float fvalue = 0; 
    char curr = 0;
    bool neg = false; 
    int index = 0; 
    for(; str[index] != '.' && str[index] != '\0'; index++)
    {   if(index==0 && str[index] == '-')
        {   neg = true; 
            continue; 
        }
        if(index==0 && str[index] == '+')
            continue; 
        curr = str[index];
        fvalue = (fvalue) * 10 + (curr-48); 
    }

    index++;
    for(int i = 10; str[index] != '\0'; i=i*10)
    {   
        curr = str[index];
        fvalue = (fvalue) + (curr-48)/(1.0*i); 
        index++; 
    }
    return neg ? 0.0-fvalue : fvalue;
    
}

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