All submissions

Convert a String to Float

Code

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

float custom_atof(const char *str) {
    // Your logic here
    int count = 0, i = 0;
    float num;
    if(str[i] == '+' || str[i] == '-')
        i = 1;
    while(str[i] != '\0')
    {
        if(count)
            count++;
        if(str[i] == '.')
            count++;
        else
            num = (num * 10) + (str[i]%48);
        i++;
    }
    while(count>1)
    {
        num = num/10;
        count--;
    }
    if(str[0] == '-')
        num = num * -1;
        
    return num;
}

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