Convert a String to Float

Code

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

float custom_atof(const char *str) {
    // Your logic here
    char symbol='+';
    int i=0;
    if(str[0]=='+' || str[0]=='-')
    {
        symbol=str[0];
        i=1;
    }
    int n=strlen(str);
    float num=0.0;
    int flag=1;
    float k=10.0;
    for(;i<n;i++)
    {
        if(str[i]=='.')
        {
            flag=0;
            continue;
        }
        else if(flag==1)
        {
            num=num*10+(str[i]-'0');
        }
        else 
        {
            float val=str[i]-'0';
            val=val/k;
            k*=10;
            num+=val;
        }
    }
    return (symbol=='-')?(-1*num):num;
}

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