Python float


Python float - Floating Point Number Datatype

float in Python is one of the basic built-in datatype among numeric types along with int and complex datatypes.

In this tutorial, we shall learn how to initialize a floating point number, what range of values it can hold, what arithmetic operations we can perform on float type 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.

In the following Python program, we have initialized variables x and y with float values.

Python Program

x = 20.85669842
y = -0.0000000008566945
print(x)
print(y)

Python Float - Print to Standard Console Output

To print a float to standard console output, we 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)

Output

20.85669842
-0.8566945
1.25563e-21

Python Float - Round to Specific Decimal Places

We 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)

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))

Output

2.09223372036859e+49
<class 'float'>

Python Float - Arithmetic Operations

We can perform all arithmetic operations on floating point numbers.

In the following example, we shall take two floating point numbers in variables a and b, and perform some arithmetic operations with these values as operands for arithmetic operators.

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)

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.