Convert a String to Float

Code

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

float custom_atof(const char *str) {
    // Your logic here
    float kq=0.0;
    int val1=0;
    int val2=0;
    int val3=1;
    
    int x=0;
    int nega=0;

    for (int i=0;str[i]!='\0';i++){
        if (i==0){
            if (str[i]=='-'){
                nega=1;
            }
            else {
                nega=0;
            }
        }
        if (str[i]<='9'&&str[i]>='0'){
            if (x==0){
            val1=val1*10+str[i]-48;
            }
            else {
                val2=val2*10+str[i]-48;
                val3*=10;
            }
        }
        else if (str[i]=='.'){
            x=1;
        
        }
    }
    kq=(float)val1+(float)(val2)/(float)val3;
    if (nega==1){
        kq*=-1;
    }
    return kq;


}

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