Convert a String to Float

Code

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

float custom_atof(const char *str) {
    float polarity = 1;
    float sum = 0;
    bool dec = false;
    float denom = 1;
    char *p = (char *)str;

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

    return (polarity * sum / denom);
}

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

 

 

 

Upvote
Downvote
Loading...

Input

123.45

Expected Output

123.45