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) {
    int neg = 1;
    int dot = 0;
    int multiplier = 1;
    float value = 0.0;
    while(*str){
        if(*str=='+'){
         str++;
         continue;
        }
        if(*str=='-') {
            neg = -1;
            str++;
            continue;
            }
        if(*str=='.'){
            dot = 1;
            str++;
            continue;
        } 
        if(dot==0){
            value = (value * 10) + (*str - '0');
        }
        else{
             multiplier = multiplier * 10;
             value = value + ((float)*str - '0')/multiplier;
        }  
        str++;
    }
    return value * neg;;
}

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