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
Liens | Site |
---|---|
round | Python Doc |
round() in Python doesn't seem to be rounding properly | stackoverflow |
How to convert 2D float numpy array to 2D int numpy array? | stackoverflow |
How to round up a complex number? | stackoverflow |
numpy.ndarray.astype | docs.scipy.org |
Using % and .format() for great good! | pyformat.info |