+3 votes
in Programming Languages by (60.0k points)
I have a list of floats, and I want to convert those floats to their nearest decimals. I do not want to convert one element at a time. Is there any way to convert them at once?
E.g.
[1.34 , 5.67 , 3.456, 9.78 ]

to

[ 1,  6,  3, 10]

1 Answer

+2 votes
by (77.2k points)
selected by
 
Best answer

Numpy's round() function returns each element rounded to the given number of decimals. The default value of the number of decimals is 0. Then you can apply astype(int) to convert them to integers.

Here is an example:

>>> import numpy as np

>>> a = np.array([1.34,5.67,3.456,9.78])

>>> a

array([1.34 , 5.67 , 3.456, 9.78 ])

>>> np.round(a)

array([ 1.,  6.,  3., 10.])

>>> np.round(a).astype(int)

array([ 1,  6,  3, 10])

>>> 


...