Python float() 3 Usage

Python float() function is used to convert other data types into floating-point numbers. Unlike integers, floating-point numbers can have decimal values. In this post, we will explore the basic usage of the float() function and its various applications.

What is Python float() Function?

The float() function in Python converts string or integer data into a floating-point number. The basic syntax is as follows:

Python
float(value)

Here, value refers to the numeric or string data you wish to convert into a floating-point number. Utilizing floating-point numbers allows for precise calculations and is useful for various mathematical operations.

Basic Usage of the float() Function

Converting Integers to Floating-point Numbers

One of the simplest ways to use float() is to convert integers into floating-point numbers.

Python
num = 17
float_num = float(num)
print(float_num)

In this example, the integer 17 is converted into the floating-point number 17.0 using the float() function. A key point to note is that when using float(), a 0 is added after the decimal point, which ensures that Python recognizes the value as a floating-point number.

Figure 1. Python converts integer 17 to floating-point number 17.0
Figure 1. Python float() converts integer 17 to floating-point number 17.0

Converting Strings to Floating-point Numbers

The float() function can also convert numeric strings into floating-point numbers.

Python
num_str = "3.14"
float_num = float(num_str)
print(float_num)

In this example, the string "3.14" is converted into a floating-point number. This is particularly useful when processing user input data, as input is often received as strings.

Figure 2. Python converts the string "3.14" into the floating-point number 3.14
Figure 2. Python float() converts the string “3.14” into the floating-point number 3.14

However, if a string cannot be converted to a number, an error will occur.

Python
num_str = "hello"
float_num = float(num_str)

This will result in a “ValueError: could not convert string to float: ‘hello'” error message.

Figure 3. ValueError occurs when trying to convert a non-numeric string with Python's float()
Figure 3. ValueError occurs when trying to convert a non-numeric string with Python float()

In such cases, you can use exception handling to manage the error:

Python
try:
    float_num = float("hello")
except ValueError:
    print("Invalid value for conversion.")

As shown below, the print() function inside the exception block is executed when the conversion fails.

Figure 4. Exception handling when the float() function cannot convert a string
Figure 4. Exception handling when the Python float() function cannot convert a string

Converting Boolean Values to Floating-point Numbers

Boolean values such as True or False can also be converted into floating-point numbers. As shown in the figure below, True is converted to 1.0 and False is converted to 0.0.

Figure 5. Python converts boolean values into floating-point numbers
Figure 5. Python float() converts boolean values into floating-point numbers

Handling Large and Small Numbers

The float() function is useful for dealing with very large or very small numbers in Python. It handles these numbers using scientific notation.

Python
large_num = 1e207
small_num = 1e-207
print(float(large_num))
print(float(small_num))

Here, 1e207 means 10^207, and the float() function efficiently processes such large numbers.

Figure 6. Python's float() function handles large and small numbers
Figure 6. Python float() function handles large and small numbers

Dealing with NaN and Inf

The float() function also handles special values like Not a Number (NaN) and Infinity (Inf). These are useful when dealing with abnormal calculation results.

Python
nan_value = float("nan")
inf_value = float("inf")
print(nan_value)
print(inf_value)

NaN represents an undefined or unrepresentable number, often occurring as a result of invalid calculations. Inf stands for infinity, which can arise when dividing by zero or when dealing with extremely large numbers. You can also use Python’s math module to handle these values:

Python
import math
nan_value = math.nan
inf_value = math.inf

Rounding with float()

When working with floating-point numbers, you often need to round them. Python allows you to adjust the number of decimal places using the round() function.

Python
num = 3.1415926535897
rounded_num = round(num, 2)  # Rounds to 2 decimal places
print(rounded_num)

As shown below, the third decimal place and beyond are rounded to fit the second decimal place.

Figure 7. Python rounds floating-point numbers using the round() function
Figure 7. Python rounds floating-point numbers using the round() function

Arithmetic Operations with float()

The float() function is frequently used in arithmetic operations. Python allows you to perform operations with both integers and floating-point numbers, and the result will automatically be converted into a floating-point number.

Python
int_num = 10
float_num = 7.3
result = int_num + float_num
print(result)

As seen below, adding an integer and a floating-point number results in a floating-point number.

Figure 8. The result of adding an integer and a floating-point number is a floating-point number in Python
Figure 8. The result of adding an integer and a floating-point number is a floating-point number in Python

The float() function is thus very useful in a wide range of arithmetic calculations.

Formatting Floating-point Output

When printing floating-point numbers, you can format the output to control the number of decimal places or the overall width of the output.

Python
pi = 3.141592
print("%8.2f" % pi)

In the example below, the number is printed with two decimal places, taking up eight spaces in total.

Figure 9. Python formats floating-point output with specified width and precision
Figure 9. Python formats floating-point output with specified width and precision

Summary

Python’s float() function is a powerful tool for converting numbers to floating-point format. It allows for precise calculations with large and small numbers, handles special values like NaN and Inf, and integrates with rounding and arithmetic operations. Additionally, when printing floating-point numbers, formatting options provide flexibility in how the results are displayed. When using float(), it’s advisable to handle exceptions properly to ensure robust code.

References

Leave a Comment