100. Convert a String to Float

Back To All Submissions
Previous Submission
Next Submission

Code

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

float custom_atof(const char *str) {
    // Your logic here

    // Your logic here
    bool mySign = true;     //assume positive number
    bool decimalFound = false;
    int decimalPos = 0;
    int myIndex = 0;
    int myDigits[3];
    int myDecimals[3];
    float myReturnValue = 0.0;
    float myOnes = 0;
    float myTens = 0;
    float myHundreds = 0;
    float myTenths = 0;
    float myHundredths = 0;
    int decades = 0;
    int decimals = 0;

    while (*str != 0x00) {
        if (*str == '-') {
            mySign = false;  // number is defined as negative
            str++;          //skip to next value
        }
        else if (*str == '+') {
            mySign = true;  // number is defined as positive
            str++;          //skip to next value
        }

        if (*str == '.') {
            decimalPos = myIndex;  //check for invalid character
            myIndex = 0;
            decimalFound = true;
            str++;          //skip over decimal
        }
        
        if(decimalFound == false){
            myDigits[myIndex++] = (*str - 0x30);
            decades++;
        }
        else{
            myDecimals[myIndex++] = (*str - 0x30);
            decimals++;
        }
        
        str++;      
    }

    switch(decimals){
        case 1:
            myHundredths = 0;
            myTenths = myDecimals[0];                 
            break;

        case 2:
            myHundredths = myDecimals[1];
            myTenths = myDecimals[0]; 
            break;

        default:
            break;
    }

    switch(decades){
        case 1:
            myHundreds = 0;
            myTens = 0;
            myOnes = myDigits[0];                 
            break;

        case 2:
            myHundreds = 0;
            myTens = myDigits[0]; 
            myOnes = myDigits[1]; 
            break;

        case 3:
            myHundreds = myDigits[0]; 
            myTens = myDigits[1]; 
            myOnes = myDigits[2]; 
            break;

        default:
            break;
    }

    myReturnValue = ((myHundreds * 100) + (myTens * 10) + myOnes) + ((myTenths / 10) + (myHundredths / 100));

    if(mySign == false) myReturnValue = -myReturnValue;

    return myReturnValue;
    return 0.0f;
}

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

 

 

 

Was this helpful?
Upvote
Downvote