All submissions

Convert a String to Float

Code

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

float custom_atof(const char *str) {
    // Your logic here
    int index=0;
    float num=0;
    char ch;
    char dot;
    int dot_count=0;
    if(str[index]=='+' || str[index]=='-'){
        ch=str[index];
        index++;
    }
    while(str[index]!='\0'){
        if(str[index]>='0' && str[index]<='9'){
            num=(num*10)+(str[index]-'0');
        }
        else if(str[index]=='.'){
            dot='.';
            dot_count=0;
        }
        index++;
        dot_count++;
    }
    int res=1;
    for(int i=0;i<dot_count-1;i++){
        res=res*10;
    }
    if(dot=='.'){
        num=num/res;
    }
    else{
        num=num*100;
        num=num/100;
    } 
    if(ch=='-'){
        return -num;
    }
    return num;
}

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