All submissions

Convert a String to Float

Code

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

float custom_atof(const char *str) {
    int sign=1,dot=0,a=0,count=10;
    float num=0,b,numf=0;
    if(((int)*str)=='-'){
        sign=-1;
        str=str+1;
    }
    else if(((int)*str)=='+'){
        sign=+1;
        str=str+1;
    }
    while(true){
        if(*str=='\0'){
            break;
        }
        if(*str=='.'){
            dot=1;
        }
        else{
            if(dot==0){
                a=((int)*str)-48;
                num=num*10+a;
            }
            else if(dot==1){
                b=((int)*str)-48;
                //printf("%d b",a);
                numf=numf+(float)b/(count);
                count*=10;
                //printf("%f f ",numf);
            }
        }
        str++;
    }
    return (num+numf)*sign;
}


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