Convert a String to Float

Code

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

float custom_atof(const char *str) {
    // Your logic here
    int posotive=0,nagative=0,decimal=0,count=0,num_count=0;
    int val = 0,div=10;
    float result = 0.0f;
    while(*str!='\0')
    {        
        if(*str=='+')
        {
            posotive =1;
        }
        else if (*str=='-')
        {
            nagative =1;
        }
        else if (*str=='.')
        {            
            decimal = count;
            if((posotive)||(nagative)) decimal--;
        }
        else if ((*str>='0')&&(*str<='9'))
        {
            val = (val*10)+(uint8_t)(*str-'0');
            num_count++;
        }
        // printf("*str=%c posotive=%d nagative=%d decimal=%d val=%.2f\n",*str,posotive,nagative,decimal,val);
        count++;
        str++;
    }    
    if(decimal)
    {
        for(int i=1; i<(num_count-decimal); i++)
        {
            div *= 10;
        }
        // printf("num_count=%d div=%d decimal=%d val=%d \n",num_count,div,num_count-decimal,val);
        result = (float)val/div;
    }
    else
    {
        result = (float)val;
    }
    return (nagative==1)?0-result: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