How To Convert String To Float In C

When writing computer programs, you may need to convert data from one format to another. For instance, converting text input from a user into a number that can be used for calculations. One type of conversion is turning a sequence of characters into a floating-point number, which is a decimal number. This is crucial when dealing with external sources or user input.

In C programming, there are functions to help you convert a string (a sequence of characters) into a float (decimal number). However, the precision (detail) of the float may be affected by the string length or formatting. Sometimes, you may also need to handle special values like infinity or NaN (which means “not a number”) when converting strings to floats.

Why is there a need to convert string to float in C ?

There are some reasons for why there may be a need to convert string to float in C :

  • User input: convert text input from users to numbers for calculations.
  • External data sources: data from files or the internet may be in string format and need to be converted to floats.
  • Interoperability: code may expect floats, but data is in string format.
  • Configuration files: configuration data in files may need to be converted to floats for use in programs.
  • Database interactions: numeric data in databases may be stored as strings and need to be converted to floats.
  • Error handling: gracefully handle non-numeric user input by converting it to a float to check validity.
  • Parsing text: extract numeric values from text strings for calculations.

Methods for converting string to float in C :

Following are the several ways to convert string to float in C :

  1. Using atof()
  2. Using sscanf()
  3. Using strtof()

A thorough explanation of each strategy:

1. Using atof():

This is a standard C library function that converts a string to a double-precision floating-point number. It takes a single argument, which is the string to be converted. The function scans the string and returns the corresponding float value. atof() is simple to use, but it does not provide any error checking or handling.

Program-

#include <stdio.h>
#include <stdlib.h>

int main() {
    // Define a string
    char str[] = "3.14159";
    
    // Convert the string to a float
    float num = atof(str);
    

    printf("Converted float: %f", num);
    

    return 0;
}

Output-

Converted float: 3.141590

Explanation:

  • The atof() function takes a string as input and returns a floating-point number.
  • In this example, we declare a string str that contains the value “3.14159”.
  • We then pass this string to the atof() function to convert it to a float.
  • The resulting float value is stored in the variable num, which is then printed using printf().

2. Using sscanf() :

This is another standard C library function that can be used to convert a string to a float. sscanf() reads formatted input from a string, which allows for more control over the conversion process. It takes two arguments: the string to be converted, and a format string that specifies the format of the input. sscanf() can handle a variety of input formats, but it may be more complicated to use than atof().

Program-

#include <stdio.h>

int main() {
    char str[] = "2.71828";  // Declare and initialize a string
    float num;               // Declare a float variable to hold the converted value
    sscanf(str, "%f", &num); // Use sscanf() to convert the string to a float
    printf("Converted float: %f", num); 
    return 0;            
}

Output-

Converted float: 2.718280

Explanation:

  • The sscanf() function reads input from a string according to a specified format and stores the result in a variable.
  • In this example, we declare a string str that contains the value “2.71828”.
  • We then call sscanf() with the format string “%f” to read a float from the string and store it in the variable num.
  • Finally, we print the resulting float value using printf().

3. Using strtof() :

This is a standard C library function that converts a string to a float, similar to atof(). However, strtof() provides more control over the conversion process. It takes three arguments: the string to be converted, a pointer to a pointer to the first character not converted, and a base that specifies the numeric base of the input. strtof() can handle a wide range of input formats and can provide error handling and reporting.

Program-

#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[] = "1.61803";  // Initialize a character array
    char *endptr;  // Declare a pointer to a character
    float num = strtof(str, &endptr);  // Use the strtof function to convert the string to a float
    printf("Converted float: %f", num); 
    return 0; 
}

Output-

Converted float: 1.618030

Explanation:

  • The strtof() function converts a string to a float, and also returns a pointer to the first character after the numeric value in the string.
  • In this example, we declare a string str that contains the value “1.61803”.
  • We then call strtof() with the input string and a pointer to a variable endptr of type char*.
  • The resulting float value is stored in the variable num, and endptr is updated to point to the first character after the numeric value in the string.
  • Finally, we print the resulting float value using printf().

Best approach for converting string to float in C :

Here are the reasons why strtof() is the best approach for converting a string to a float in C:

  • Efficient: strtof() is optimized for speed and memory usage, and extensively tested for accuracy.
  • Flexible: strtof() can handle a wide range of input formats, with options for error handling.
  • Consistent: strtof() is a standardized function available on most platforms, making it reliable for cross-platform development.
  • Type safe: strtof() ensures the output is a float, useful for compatibility with other code.
  • Easy to use: strtof() only requires a single line of code to convert a string to a float, making it convenient for most use cases.

Sample Problems:

Problem 1:

Write a C program that takes input as a temperature data in string format from a sensor and uses the atof() approach to convert it into a float data type. The converted data should then be used for performing necessary calculations.

Solution-

  • Declare character array tempStr and float variable temperature.
  • Prompt users to enter temperature data as a string using printf().
  • Read user input and store it in tempStr using scanf().
  • Convert tempStr to a float using atof() and store in temperature.
  • Print temperature data as float with 2 decimal places using printf() and %.2f format specifier.
  • Convert temperature data from Kelvin to Celsius by subtracting 273.15 and print it with 2 decimal places using printf().
  • Print temperature data in Kelvin with 2 decimal places using printf().
  • Return 0 to indicate successful execution.

Program-

#include <stdio.h>
#include <stdlib.h>

int main() {
    char tempStr[10]; // declare a character array to store temperature data as string
    float temperature; // declare a float variable to store temperature data as float

    printf("Enter temperature data as string: ");
    scanf("%s", tempStr); // read temperature data as string from user input and store in tempStr

    temperature = atof(tempStr); // convert temperature data from string to float using atof() function and store in temperature

    printf("Temperature data as float: %.2f\n", temperature); // print temperature data as float with 2 decimal places
    printf("Temperature in Celsius: %.2f\n", temperature - 273.15); // convert temperature data from Kelvin to Celsius and print with 2 decimal places
    printf("Temperature in Kelvin: %.2f\n", temperature); // print temperature data as Kelvin with 2 decimal places

    return 0;
}

Output-

Enter temperature data as string: 298.15
Temperature data as float: 298.15
Temperature in Celsius: 25.00
Temperature in Kelvin: 298.15

Problem 2:

Write a C program to convert financial data provided as strings, representing currency amounts like $10.25, into floats using the sscanf() approach for performing calculations.

Solution-

  • In main(), currencyStr (char array) and currencyAmt (float variable) are declared to store input string and converted value, respectively.
  • Users are prompted to enter a currency amount using printf().
  • Input string is read from the user and stored in currencyStr using scanf().
  • sscanf() extracts float value from currencyStr and stores it in currencyAmt.
  • Converted value is displayed with a dollar sign using printf() and “%.2f” format specifier.
  • Program ends with return 0 indicating successful execution.

Program-

#include <stdio.h>

int main() {
    char currencyStr[10]; // stores input string
    float currencyAmt; // stores converted float value

    printf("Enter currency amount as a string: ");
    scanf("%s", currencyStr); 

    // use sscanf to extract float value from input string
    sscanf(currencyStr, "%f", &currencyAmt);

    printf("Currency amount as float: $%.2f\n", currencyAmt);

    return 0;
}

Output-

Enter currency amount as a string: 10.25
Currency amount as float: $10.25

Problem 3:

Write a C program that reads the heart rate data as a string from a fitness tracker and converts it to a float using the strtof() approach. The program should then track the user’s progress over time by keeping a record of their highest and lowest heart rate readings.

Solution-

  • Read heart rate data from user using scanf()
  • Convert string to float using strtof() and store in a variable
  • Check if the current heart rate is higher than the previous maximum heart rate value and update if necessary.
  • Check if the current heart rate is lower than the previous minimum heart rate value and update if necessary.
  • Loop to allow users to enter new heart rate data until they quit.

Program-

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

int main() {
    char heartRateStr[10]; // stores input string
    float heartRate; // stores converted float value
    float maxRate = 0.0, minRate = 999.0; // initialize max and min heart rate values

    // loop to read heart rate data and track progress over time
    while(1) {
        printf("Enter heart rate data as a string: ");
        scanf("%s", heartRateStr); // reads input string from user

        // use strtof to convert string to float
        heartRate = strtof(heartRateStr, NULL);

        printf("Heart rate as float: %.2f\n", heartRate);

        // check if current heart rate is higher than previous max
        if(heartRate > maxRate) {
            maxRate = heartRate;
            printf("New max heart rate: %.2f\n", maxRate);
        }

        // check if current heart rate is lower than previous min
        if(heartRate < minRate) {
            minRate = heartRate;
            printf("New min heart rate: %.2f\n", minRate);
        }
    }

    return 0;
}

Output-

Enter heart rate data as a string: 72.1
Heart rate as float: 72.10
New max heart rate: 72.10
New min heart rate: 72.10
Enter heart rate data as a string: 80.4
Heart rate as float: 80.40
New max heart rate: 80.40
Enter heart rate data as a string: 50
Heart rate as float: 50.00
New min heart rate: 50.00

Conclusion

In conclusion, converting a string to a float is a common operation in programming, especially when dealing with user input. It allows for numerical calculations and comparisons to be performed on the input data.

C programming languages provide built-in functions for converting strings to float, such as atof() in C, parseFloat() in JavaScript, and parseFloat() in Python.

It is important to ensure that the input string is properly formatted and validated before attempting to convert it to a float, as invalid input can cause errors or produce unexpected results.