100. Convert a String to Float

Back To All Submissions
Previous Submission
Next Submission

Code

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

float custom_atof(const char *str) {
    // Your logic here
    bool decf=false;
    float n=0;
    int k=1;
    bool sigp, siga, sig;
    sigp=(*str=='+' || *str =='-')?true:false;
    sig=(*str=='+')?true:false;
    siga=sigp;

    while(*str){
        if(sigp){
            sigp=false;
        }
        else{
            //printf("%f ",n );
            if(*str=='.') decf=true;
            if(!decf){

            n=(10*n) + (*str-'0');
            
            }
            else if(*str!='.'){
            //printf("%f ",(*str-'0')/pow(10,k));
            //printf("%c ",*str);
            n=n+((*str-'0')/pow(10,k));
            k++;
            }
        }
        str++;
    }
    n=(sig||!siga)?n:-n;

    return n;
}

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