Convert a String to Float

Code

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

float convert_str_to_float(char *str){
    int sign = 1;
    int count = 0;
    int flag = 0; 
    int integer_part = 0; 
    int decimal_part = 0;
    int decimal_count = 1;
    if((str[count] == '-') || (str[count]  == '+')){
        if(str[count] == '-' ){
            sign = -1;
        }
        count++;
    }
    while(str[count] != '\0'){
        if(str[count] == '.'){
            flag = 1;
            count++;
        }
        if(flag == 0){
            integer_part = integer_part*10 + (str[count] - '0');
        }
        else if(flag == 1){
            decimal_part = decimal_part*10 + (str[count] - '0');
            decimal_count *= 10;
        }
        count++; 
    }
    
    return sign*((float)integer_part + (float)decimal_part/(decimal_count));
}

int main(){
    char str[101];
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';

    printf("%.2f",convert_str_to_float(str));
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

123.45

Expected Output

123.45