How to round a number in python ?

Published: March 21, 2019

DMCA.com Protection Status

Examples of how to round a number in python:

Round a float number

To round a number in python, a solution is to use the function round :

>>> round(3.1415)
3

Round a float number (keep 1 digit after the decimal point)

>>> x = 1.4567
>>> round(x,1)
1.5

Round a float number (keep 2 digits after the decimal point)

>>> x = 1.4567
>>> round(x,2)
1.46

Change a float to int

>>> x = 3.1415
>>> x = int(x)
>>> x
3
>>> type(x)
<class 'int'>

same as

>>> x = round(3.1415)
>>> type(x)
<class 'int'>
>>> x
3

Round the elements of an array

To round the element of an array a solution is to use the numpy function around, example:

>>> import numpy as np
>>> a = np.array(([1.24,3.46,5.34]))
>>> a
array([1.24, 3.46, 5.34])
>>> np.around(a, decimals=1)
array([1.2, 3.5, 5.3])

To convert a float array to a integer array, a solution is to use astype:

>>> import numpy as np
>>> a = np.array(([1,24,3.46,5.34]))
>>> a
array([ 1.  , 24.  ,  3.46,  5.34])
>>> a.astype(int)
array([ 1, 24,  3,  5])

Round a complex number

>>> z = 2.14 + 3.47j
>>> round(z.real, 1) + round(z.imag, 1) * 1j
(2.1+3.5j)

Use format

if the goal of rounding a number is to add it to a string, a solution is to use format()

>>> s = 'Pi value is {:06.2f}'.format(3.141592653589793)
>>> s
'Pi value is 003.14'
>>> s = 'Pi value is {:01.2f}'.format(3.141592653589793)
>>> s
'Pi value is 3.14'

References