100. Convert a String to Float

Back To All Submissions
Previous Submission
Next Submission

Code

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

float custom_atof(const char *str) {
    // Your logic here
    float res = 0;
    int count =0;
    int front = 0;
    float end = 0;
    int isNegetive=1;
    int i=0;
    if(str[0]=='-'){
        isNegetive = -1;
        i++;
        }
    else if(str[0]=='+'){
        i++;
    }
    
    while (str[i] !='\0' && str[i]!='.')
    {
        front=(str[i]-'0')+front*10;
       i++;
    }
    i=i+1;
    while (str[i] !='\0')
    {
        count++;
        end=(str[i]-'0')+end*10;
       i++;
    }
    int val=1;
    for(int i=0;i<count;i++){
        val*=10;
    }
    res=front+(end/val);
    return res*isNegetive;
}

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

 

 

 

Was this helpful?
Upvote
Downvote