All submissions

Convert a String to Float

Code

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

float custom_atof(const char *str) {
    char *p = (char *)str;
    int sum = 0;
    bool fraction = false;
    int polarity = 1;
    int digits = 0;

    while (*p) {
        if (*p >= '0' && *p <= '9') {
            sum *= 10;
            sum += *p - '0';
            if (fraction)
                digits++;
        } else if (*p == '+') {
            polarity = 1;
        } else if (*p == '-') {
            polarity = -1;
        } else if (*p == '.') {
            fraction = true;
        }
        p++;
    }

    return (float)polarity * (float)sum * (float)pow(10, -digits);
}

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