Convert a String to Float

Code

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

float custom_atof(const char *str) {
    // Your logic here
    int cnt =0;
    int cnt_2 =0;
    char switch_t =0;
    float retval =0;
    float fraction =0;
    int divisor =1;
    
    while(str[cnt]!=0){
        if((str[cnt]>='0' && str[cnt]<='9') && !switch_t){
            retval = (retval*10)+str[cnt]-'0';
            
        }
        else if(str[cnt] == '.'){
            switch_t = 1;
        }
        else if((str[cnt]>='0' && str[cnt]<='9')){
            fraction = (fraction*10)+str[cnt]-'0';
            divisor*=10;
        }
        cnt++;
    }
    retval +=  fraction/divisor;
    if(str[0]=='-'){
        retval*=-1;
    }
    return retval;
}

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