All submissions

Convert a String to Float

Code

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

float custom_atof(const char *str) {
    // Your logic here
    const char *point = str;
    const char *start = str;
    const char *end = str;
    int f = 1;

    /* find + - */
    f = (*start == '-')? -1 : f ;
    /* start position */
    start =  ((*start == '+')||(*start == '-'))? start+1 : start ; 
    /* find point */
    while((*point != '.') && (*point))
        point+=1;
    /* find end */
    while(*end)
        end+=1;

    float a = 0;
    float b = 0; 
    if(point != end)
    {        float mfactor = 1;
        while(point - start)
        {
            int len = point - start ;
            int factor = 1;
            for(int n = 0 ; n < len-1 ; n++)
                factor *= 10;
            a += (*start - 48) * factor ;
            start++;
        }

        point+=1;
        for(int n = 0 ; n < (end-point) ; n++)
          mfactor *= 10;

          while(end - point)
        {
            int len = end - point ;
            int factor = 1;
            for(int n = 0 ; n < len-1 ; n++)
                factor *= 10;
            mfactor = (factor > mfactor)? factor : mfactor;
            b += (*point - 48) * factor ;
            point++;
        }
       // printf("%f ",mfactor);

        a = a + (b * 1/mfactor);
    }
    else 
    {
        a=0;
        int len = end - start ;
        int factor = 1;
        for(int n = 0 ; n < len-1 ; n++)
                factor *= 10;
        while(end - start)
        {
            a += (*start - 48) * factor ;
            start++;
        }
    }

    return a * f;
}

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

 

 

 

Loading...

Input

123.45

Expected Output

123.45