float data type, float() function, & float methods - Python


Introduction

Python is a flexible and powerful programming language that can work with different data types, such as whole numberstextdecimal numbers, etc.

In this article, we will look into what float is, how to use them, and provide example codes to help understand them better.

float data type in Python

In Python, a float is a built-in data type representing real numbers. A float is used to represent a decimal value, and they are stored in memory as a binary fraction. 

They are called "float" because the decimal point can "float" to represent values of varying magnitudes. It helps express numbers that have a fractional value, like money or scientific measurements.

A float can be created by simply assigning a decimal value to a variable:

my_float = 3.14159

Python also supports scientific notation for creating a float, using the letter "e" to represent exponents:

my_float = 1.23e-4 # equivalent to 0.000123

Example - Operations with Float data type

In Python we can perform various mathematical operations such as addition, subtraction, multiplication, and division with float data types. Here's a Python code example -

a = 5.45
b = 3.54

# Addition
addedOp = a + b

# Subtraction
subtractedOp = a - b

# Multiplication
multipliedOp = a * b

# Division
dividedOp = a / b

print(addedOp)
print(subtractedOp)
print(multipliedOp)
print(dividedOp)

The Output will be -

8.99
1.9100000000000001
19.293
1.53954802259887

Explanation:

The above code demonstrates four arithmetic operations (addition, subtraction, multiplication, and division) performed on two floating-point numbers, a and b. The arithmetic operations are performed using the standard arithmetic operators (+-*, and /), and the results are assigned to corresponding variables (addedOp, subtractedOp, multipliedOp, and dividedOp).

Besides the fundamental math operations, Python also offers built-in methods to handle float data type.

float() function in Python

In Python, float() is a built-in function that can convert a value to a floating-point number. It takes a single argument, which can be a number or a string that represents a number, and returns a float value.

If the argument is a stringfloat() will attempt to convert it to a float value. If the string contains a valid floating-point number, the function will return that number. If the string cannot be converted to a float, float() will raise a ValueError.

Let's look at an example of using float() in Python -

Example

Below is the Python code -

# Converting an integer to a float
x = 5
y = float(x)
print(y)   # Output: 5.0

# Converting a string to a float
a = "3.14159"
b = float(a)
print(b)   # Output: 3.14159

# Attempting to convert an invalid string to a float
c = "hello"
d = float(c)  # Raises ValueError: could not convert string to float

The Output will be -

5.0
3.14159
ValueError: could not convert string to float: 'hello'

Explanation:

In the above example,

  • First, an integer value 5 is converted to a floating-point number using the float() function and assigned to the variable y. The resulting floating-point value is printed to the console, which is 5.0.
  • Second, a string value "3.14159" is converted to a floating-point number using the float() function and assigned to the variable b. The resulting floating-point value is printed to the console, which is 3.14159.
  • Third, an invalid string "hello" is attempted to be converted to a floating-point number using the float() function, which raises a ValueError exception because the string cannot be converted to a valid floating-point number.

Note: The float() function can sometimes result in rounding errors because floating-point numbers are stored and manipulated in a computer's memory. Therefore, when dealing with financial or other sensitive calculations, it's recommended to use decimal arithmetic or other specialized libraries to handle floating-point numbers.

Common Float methods in Python

In Python, float is a built-in data type, and it has a few useful methods that can be used to manipulate and work with float values. 

The float class creates floating-point objects, which can be assigned to variables or used in mathematical operations. The float class also provides various methods for working with floating-point numbers.

Here are some of the most commonly used float methods:

  1. as_integer_ratio()
  2. is_integer()
  3. hex()
  4. format()
  5. round()
  6. float.fromhex()

Let's understand each of them.

as_integer_ratio()

The as_integer_ratio() method in Python returns a tuple containing the numerator and denominator of a float value represented as a fraction. This method helps deal with fractions and converts float data to rational number.

Here are some examples:

Example 1

Below is the Python code -

a = 2.24

numerator, denominator = a.as_integer_ratio()

print(numerator)
print(denominator)

The Output will be -

1261007895663739
562949953421312

Explanation:

In the above example,

  • We create a float variable "a" with the value of 2.24.
  • Then we use the as_integer_ratio() method to get the numerator and denominator of the fraction that approximates "a".
  • Lastly, we unpack the result into "numerator" and "denominator" variables and print them to the console.

Example 2

Below is the Python code -

import fractions

x = fractions.Fraction(5, 10)
numerator, denominator = x.as_integer_ratio()
print(numerator, denominator)

The Output will be -

1 2

Explanation:

In the above example,

  1. First, we import the fractions module.
  2. Then we create a Fraction object x with the numerator 5 and denominator 10. This represents the fraction 1/2. The Fraction constructor automatically simplifies the fraction by dividing both the numerator and denominator by their greatest common divisor.
  3. Then we call the as_integer_ratio() method on the Fraction object x. This method returns a tuple containing the numerator and denominator of the fraction represented as integers in their simplest form. In this case, the tuple (1, 2) is returned.
  4. Next, we unpack the tuple into two variables numerator and denominator.
  5. Lastly, we print the values of the numerator and denominator, which are 1 and 2, respectively. These are the integer values of the fraction 1/2.

Example 3

Below is the Python code -

x = 2.5
y = x.as_integer_ratio()
print(y)

The Output will be -

(5, 2)

Explanation:

In the above example,

  1. First, we set the value of the variable x to 2.5.
  2. Next, we call the as_integer_ratio() method on the float object x. This method returns a tuple containing the numerator and denominator of the fraction represented as integers in their simplest form. In this case, the tuple (5, 2) is returned because 2.5 is equivalent to the fraction 5/2.

is_integer()

The is_integer() method in Python tests whether a float is an integer. It returns True if the float is an integer and False otherwise.

Here are some examples:

Example 1

Below is the Python code -

a = 2.0
b = 2.24

print(a.is_integer())
print(b.is_integer())

The Output will be -

True
False

Explanation:

This above code demonstrates the use of the is_integer() method of the float class in Python. We set the values of two variables, a and b, to floating-point numbers and then prints the results of calling the is_integer() method on each variable. The output shows True if the number is an integer and False if it has a fractional part.

Example 2

Below is the Python code -

import math
num = math.inf
if num.is_integer():
    print("The number is an integer")
else:
    print("The number is not an integer")

The Output will be -

The number is not an integer

Explanation:

In the above code,

  • We use the math module in Python to assign the value of infinity to a variable called num.
  • Then we check whether num is an integer by calling the is_integer() method on num.
  • Since infinity is not an integer, the code output will be "The number is not an integer".

Example 3

Below is the Python code -

x = 3.0
y = x.is_integer()
print(y)

x = 2.5
y = x.is_integer()
print(y)

The Output will be -

True
False

Explanation:

In the above code,

  • We set the values of variable x to floating-point numbers twice and then call the is_integer() method each time.
  • The is_integer() method returns True if the floating-point number has no fractional part (i.e., it represents an integer) and False otherwise.
  • The code output will be True for the first case where x is set to 3.0 and False for the second case where x is set to 2.5.

hex()

The hex() method in Python returns a hexadecimal string representation of the float. This method is beneficial for binary data operations and converting float data type to a more concise form.

Here are some examples:

Example 1

Below is the Python code -

a = 2.24
hex_value = a.hex()
print(hex_value)

The Output will be -

0x1.1eb851eb851ecp+1

Explanation:

In the above example,

  • We create a float variable "a" with a value of 2.24.
  • Then we apply the hex() method to "a", which gives a string representing the hexadecimal value of "a".
  • Lastly, we print the result to the console.

Example 2

Below is the Python code -

import math
not_a_num = math.nan
hex_nan = float.hex(not_a_num)
print(hex_nan)

The Output will be -

nan

Explanation:

In the above code, the float.hex() method converts a NaN (not a number) value to its hexadecimal representation. The resulting string contains the character "nan", the standard representation for NaN values in hexadecimal format.

format()

The format() method in Python allows us to format a float value as a string. It takes a format specification string as an argument.

Let's look at some examples.

Example 1

Below is the Python code -

x = 3.14159
y = format(x, ".2f")
print(y)

The Output will be -

3.14

Explanation:

In the above code,

  • We set the value of the variable x to a floating-point number and then use the format() method to format x with two decimal places
  • The formatted value is then assigned to the variable y and printed to the console. The code output will be 3.14, the value of x rounded to two decimal places.

Example 2

Below is the Python code -

x = 12345.6789
y = format(x, ".3e")
print(y)

The Output will be -

1.235e+04

Explanation:

In the above code,

  • The format() method of the float class is used to format the floating-point number x in scientific notation with 3 digits after the decimal point.
  • The formatted string is then assigned to the variable y, which is printed to the console. The code output will be "1.235e+04", which is x formatted in scientific notation with 3 decimal places.

Example 3

Below is the Python code -

x = 3.14159
y = format(x, "8.4f")
print(y)

The Output will be -

  3.1416

Explanation:

In the above code,

  • The format() method of the float class is used to format the floating-point number x with a total width of 8 characters and 4 digits after the decimal point.
  • The formatted string is then assigned to the variable y, which is printed to the console.
  • The output of the code will be "  3.1416", which is x formatted with a total width of 8 characters and 4 decimal places. The output includes two leading spaces to fill the remaining width of 8 characters.

round()

The round() method in Python allows us to round a float value to a specified number of decimal places. It takes an optional argument that specifies the number of decimal places to round to.

Let's look at some examples.

Example 1

Below is the Python code -

x = 3.14159
y = round(x, 2)
print(y)

The Output will be -

3.14

Explanation:

In the above code,

  • We set the value of the variable x to a floating-point number and then use the round() method to round x to 2 decimal places.
  • The rounded value is then assigned to the variable y, which is printed to the console. The output of the code will be 3.14, which is the value of x rounded to 2 decimal places.

Example 2

Below is the Python code -

x = 3.14159
y = round(x, 4)
print(y)

The Output will be -

3.1416

Explanation:

In the above code,

  • The round() method of the float class is used to round the floating-point number x to 4 decimal places.
  • The rounded value is then assigned to the variable y, which is printed to the console. The output of the code will be 3.1416, which is the value of x rounded to 2 decimal places using the round() method.

Example 3

Below is the Python code -

x = 3.14159
y = round(x)
print(y)

a = 5.625
b = round(a)
print(b)

The Output will be -

3
6

Explanation:

In the above code,

  • First, we set the variable x to a floating-point number, and then we call the round() method on it without any argument, which rounds it to the nearest integer. The rounded value is assigned to the variable y, which is printed to the console.
  • Second, we set the variable a to another floating-point number and call the round() method on it without any argument, which also rounds it to the nearest integer. The rounded value is assigned to the variable b, which is printed to the console.

float.fromhex()

Python's float.fromhex() method in Python makes a new float object from a hexadecimal string. This method is the opposite of the hex() method, which gives the hexadecimal string representation of a float.

Let's take a look at examples to see how this method works:

Example 1

Below is the Python code -

hex_str = '0x1.1eb851eb851ecp+1'
f = float.fromhex(hex_str)
print(f)

The Output will be -

2.24

Explanation:

In this above example,

  • We begin with a hexadecimal string, "hex_str", which represents '0x1.1eb851eb851ecp+1'.
  • Then, we use the float.fromhex() method on this string to produce a new float object "f" with a value of 2.24.
  • Lastly, we print the value of "f" to the console.

Example 2

Below is the Python code -

hex_str = '-0x1.8p-2'
num = float.fromhex(hex_str)
print(num)

The Output will be -

-0.375

Explanation:

In this above example,

  • We first created a string hexstr that contains a negative float number in hexadecimal format.
  • The float.fromhex() method then converts this string back to its corresponding float number, considering the negative exponent.
  • The resulting float value num is then printed to the console.

Example 3

Below is the Python code -

x = float.fromhex('0x1.921f9f01b866ep+1')
print(x)

The Output will be -

3.14159

Explanation:

In this above example,

  • The hexadecimal string '0x1.921f9f01b866ep+1' represents a floating-point number passed as an argument to the float.fromhex() method.
  • The resulting float value is assigned to the variable x, which is printed to the console.

Note:
hex() is an instance method in Python, which means it is called on a float object. It returns a hexadecimal string representation of the float, which can be used to recreate the float later using the float.fromhex() method.

On the other hand, float.fromhex() is a class method in Python, which means it is called on the float class itself rather than on a specific instance of the class. It creates a new float object from a hexadecimal string representation.

Conclusion

In this blog, we looked at float data type, float() function, and different methods of float class in Python.

These methods help perform various operations, such as converting float data type to rational number, working with binary data, checking whether a float is an integer, etc.

Overall, the float class in Python provides a versatile and convenient way to work with floating-point numbers in a wide range of applications.

I hope you found this article helpful.

float data type, float() function, & float methods - Python - FI

You may like to Explore -

6 Ways to add new column to existing DataFrame – Pandas | Python

set add() Method – Python | Explained with Examples

os.listdir() Method – Python | Explained with Examples

Cheers!

Happy Coding.

About the Author

This article was authored by Satyam Tripathi. Verified by Rawnak.