All submissions

Convert a String to Float

Code

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


float custom_atof(const char *str) {
    int head = 0;
    int mul = 1;
    float num = 0;
    int dot = 0;
    int count = 0;

    if (str[head] == '-' || str[head] == '+') {
        mul = (str[head] == '-') ? -1 : 1;
        head++;
    }
    
    for(; str[head] !='\0'; head++){
        if (str[head] == '.') {
            // if (dot) break;
            dot = 1;
            continue;
        }
         
        if (str[head] >= '0' && str[head] <= '9'){
            num = num * 10 + (str[head] -'0');
            if(dot) count++; 
        }
    }

    while (count--) {
        num /= 10.0f;
    }

 return num*mul;
}



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