Convert a String to Float

Code

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

float custom_atof(const char *str) {
    // Your logic here
    int sign = 0;
    float result = 0.0f;
    int decimal = 0;
    bool nbr = false;
    while (*str){
        if ((!(sign)) && ((*str == '-') || (*str == '+'))) { //determine sign
            if (*str=='-') sign = -1;
            else if (*str=='+') sign = 1;
        }
        else
        if ((*str >= '0') && (*str <='9')) { //is number
            result = result*10 + ((char)*str - '0');
            if (!(decimal==0))  decimal = decimal*10;
            nbr = true; //space not accepted anymore
            if (!(sign)) sign = 1; //no +/- at start
        }
        else if (*str == '.') {decimal = 1.0f; } 
        else  //not number 
            if ((*str==' ') && (!nbr)) {} //just ignore
            else  {
                if (!decimal) decimal=1;
                return (sign* (result/decimal));
                }
            
    str++;
    }
    if (!decimal) decimal=1; //for number wthout '.'
    return (sign* (result/decimal));
}

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