Convert a String to Float

Code

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

float custom_atof(const char *str) {
    // Your logic here
    int is_negative = 0;
    int is_posiitve = 0;
    int decimal_pos = 1;
    int no_of_digits = 0;

    if(str[0] == '-')
    {
        is_negative = 1;
    }
    else if(str[0] == '+')
    {
        is_posiitve = 1;
    }
    else
    {
        is_posiitve = 1;
    }



    while(1)
    {
        if(str[decimal_pos] == '.')
           { break;}
        
        decimal_pos++;
    }
    
    // printf("decima_pos:%d\n",decimal_pos);

    int pos = 0;
    float result = 0;

    while (str[pos] != '\0') 
    {
        
        if(is_posiitve || is_negative)
        {
            char ch = str[pos + 1];
        }
        else
        {
            char ch = str[pos];
        }        

        if(str[pos] >= '0' && str[pos] <= '9')
        {
            result = (result * 10) + (str[pos] - '0');
        }
        pos++;
        no_of_digits++;

    }

    int divisor = 1;

    int no_after_decimal =  no_of_digits - decimal_pos;

    for (int i = 1; i < no_after_decimal; i++) {
        divisor *= 10;
    }

    // printf("divisor:%d\n",divisor);

    result = result / divisor;

    if(is_negative)
    {
        result = result * -1;
    }

    return 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