Convert a String to Float

Code

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

float power(int num, int exp)
{
    float result = 1;
    if(exp > 0)
    {
         while(exp--)
        {
            result *= num;
        }   
    }
    else
    {
        exp = ~(exp) + 1;
        while(exp--)
        {
            result *=(1/(float)num);
        }
    }
    return result;
}

float custom_atof(const char *str) {
    // Your logic here
    float num = 0;
    
    int len = -1;
    while(str[++len] != '\0');
    
    int integer[255] = {0};
    int decimal[255] = {0};
    
    bool dot_found = false;
    int d_count = 0;
    int i_count = 0;
    bool isNegative = false;

    for(int i=0; i<len; ++i)
    {
        if(str[i] == '.')
        {
            dot_found = true;
            continue;
        }
        else if(str[i] == '+')
        {
            continue;
        }
        else if(str[i] == '-')
        {
            isNegative = true;
            continue;
        }
        if(!dot_found)
        {
            integer[i_count++] = str[i]-'0';
        }
        else
        {
            decimal[d_count++] = str[i]-'0';
        }
    }
    for(int i=0; i<(i_count/2); ++i)
    {
        int temp = integer[i];
        integer[i] = integer[i_count-1-i];
        integer[i_count-1-i] = temp;
    }
    int exp =0;
    exp = -1;
    float d_part =0;
    int i_part = 0;
    for(int i=0; i<d_count; ++i)
    {
        d_part += decimal[i]*power(10,exp);
        exp--;
    }
    exp = 0;
    for(int i=0; i<i_count; ++i)
    {
        i_part += integer[i]*power(10,exp);
        exp++;
    }
        if(isNegative)
    {
        i_part = ~i_part +1;
        num = i_part-d_part;
    }
    else
    {
      num = i_part+d_part;   
    }
    return 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