All submissions

Convert a String to Float

Code

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

float custom_atof(const char *str) 
{
   float factor=10;
   float ans=0.0f;
   char n_flag=1;
   int i=0;
   if(str[i]=='-') //if the first character is operator like '+ or '-'. Then we need to skip it and mark the flag for '-' operator.
   {
     n_flag=-1;
     i++;
   }

   if(str[i]=='+') //if the first character is '+' operator, then we skip it.
     i++;

   char fraction_flag=0;
   
   while(str[i])
   {
     if(str[i]=='.')
     {
       fraction_flag=1; //whenever we find '.' while travesing through string, we skip the current character and set the fraction_flag to high.
       i++;
       continue;
     }

      if(fraction_flag) //We need to have seperate logic for calculating fractional part.
      {
        ans=ans+((str[i]-'0')/(float)factor);
        factor=factor*10;
      }
      else 
      {
        ans=(ans*10)+(str[i]-'0');
      }
      //printf("Value of ans:%f\n",ans);
    i++;
   }
    
    return (ans*n_flag); //if the first character is '-' operator, then we return negative value because flag is set as -1.
}

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