Python float

Python float – Floating Point Number Datatype

float keyword in Python represents a floating point number. float is one of the basic built-in datatype among numeric types in Python along with int and complex.

In this tutorial, we shall learn what a float datatype in Python is, how to initialize a floating point number, what range of values it can hold, what arithmetic operations we can perform on float numbers, etc.

Python float – Initialize

To initialize a variable with float value, use assign operator and assign the floating point value to the variable. Variable name has to be on the left hand side and the float value has to be on the right side.

Following is a simple example, we have two statements that initialize x with a float value and also y with a float value.

x = 20.85669842
y = -0.0000000008566945
Run this program

Python float – Print to Standard Console Output

To print a float to standard console output, you can use built-in function print(). print() accepts float as argument.

In the following example, we shall initialize a variable with float value and print it to console.

Python Program

x = 20.85669842
y = -0.8566945
z = 0.00000000000000000000125563

print(x)
print(y)
print(z)
Run this program

Output

20.85669842
-0.8566945
1.25563e-21
Run this program

Python Float – Round of to Specific Decimal Places

You can round of a given floating point number, to a specific number of decimal places using round() function.

In the following example, we shall take a float value with 7 decimal places and round it of to 2 decimal places.

Python Program

a = 3.1458698
a = round(a, 2)
print(a)
Run this program

Output

3.15

The first argument to round() function is the value which we have to truncate and the second argument is the number of decimal places it has to be truncated to.

Python Float – Range or Bounds

As of Python 3, there is no bound on the maximum or minimum value a float variable can hold.

In the following example, let us take some very large floating number and validate its type.

Python Program

x = 20922337203685899999999999999999999998542114775897.999999999999942211

print(x)
print(type(x))
Run this program

Output

2.09223372036859e+49
<class 'float'>
Run this program

Python Float – Arithmetic Operations

You can perform all arithmetic operations on floating point numbers.

In the following example, we shall perform some arithmetic operations.

Python Program

a, b = 3.14, 4.32

#addition
print(a+b)

#subtraction
print(a-b)

#multiplication
print(a*b)

#integer division
print(a//b)

#float division
print(a/b)
Run this program

Output

7.460000000000001
-1.1800000000000002
13.564800000000002
0.0
0.7268518518518519

Summary

In this tutorial of Python Examples, we learned about different aspects of float in Python.