All submissions

Convert a String to Float

Code

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

/**
 * Converts a string representing a floating-point number to a float.
 * Handles optional sign, integer part, and fractional part.
 */
float custom_atof(const char *str) {
    int sign;
    int index;
    float num;

    // Initialize variables
    sign = 0;
    index = 0;
    num = 0.0;

    // Handle the optional sign at the start of the string
    if(str[index] == '+')
    {
        sign = 1;       
        index++;        
    }
    else if(str[index] == '-')
    {
        sign = -1;      
        index++;        
    }

    // Parse the integer part before the decimal point
    while(str[index])
    {
        if(str[index] == '.')
        {
            index++;    
            break;      // Start parsing fractional part
        }
        // Convert character to digit and accumulate
        num = num * 10 + str[index] - '0';
        index++;
    }

    float divisor = 10.0;
    // Parse the fractional part after the decimal point
    while(str[index])
    {
        // Convert character to digit and add fractional value
        num += (str[index] - '0') / divisor;
        divisor *= 10;  // Increase divisor for next decimal place
        index++;
    }

    // Apply sign if negative
    if(sign == -1)
        num *= sign;
    return num;
}

int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);

    // Remove trailing newline character from input
    uint8_t i = 0;
    while (str[i]) {
        if (str[i] == '\n') {
            str[i] = '\0';
            break;
        }
        i++;
    }

    float value = custom_atof(str);
    // Print the converted float with two decimal places
    printf("%.2f", value);
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

123.45

Expected Output

123.45