All submissions

Convert a String to Float

Code

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

float custom_atof(const char *str) {
    int i = 0,neg = 1,flag = 0,mul = 0,fact = 1,end = 0,dot_flag = 0;
    float final_val = 0,final_val_1 = 0;
    if(str[i] == '-'){
        neg = -1;
    }
    if(str[i] == '-' || str[i] == '+'){
        end = 1;
    }
    while(str[i] != '\0'){
        if(str[i] == '.'){
            dot_flag =1;
        }
        i++;
    }
    i-=1;
    while(i >= end){
        if(dot_flag == 0){
            flag = 1;
        }
        if(str[i] == '.'){
            flag = 1;
            i--;
            continue;
        }
        if(!flag){
            final_val = (final_val/10.0) + ((str[i] - '0') /10.0);
        }
        else{
            fact = 1;
            for(int ptr = 0;ptr<mul;ptr++){
                fact = fact*10;
            }
            final_val_1 = (final_val_1) + ((str[i] - 48)*fact) ;
            mul++;;
        }
        i--;
        
    }
    return (neg*(final_val + final_val_1));
}

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