# [python] How to round a numpy array?

I have a numpy array, something like below:

``````data = np.array([  1.60130719e-01,   9.93827160e-01,   3.63108206e-04])
``````

and I want to round each element to two decimal places.

How can I do so?

This question is related to `python` `arrays` `numpy` `rounding`

If you want the output to be

``````array([1.6e-01, 9.9e-01, 3.6e-04])
``````

the problem is not really a missing feature of NumPy, but rather that this sort of rounding is not a standard thing to do. You can make your own rounding function which achieves this like so:

``````def my_round(value, N):
exponent = np.ceil(np.log10(value))
return 10**exponent*np.round(value*10**(-exponent), N)
``````

For a general solution handling `0` and negative values as well, you can do something like this:

``````def my_round(value, N):
value = np.asarray(value).copy()
exponent = np.ceil(np.log10(value))
result = 10**exponent*np.round(value*10**(-exponent), N)
return result
``````

It is worth noting that the accepted answer will round small floats down to zero.

``````>>> import numpy as np
>>> arr = np.asarray([2.92290007e+00, -1.57376965e-03, 4.82011728e-08, 1.92896977e-12])
>>> print(arr)
[ 2.92290007e+00 -1.57376965e-03  4.82011728e-08  1.92896977e-12]
>>> np.round(arr, 2)
array([ 2.92, -0.  ,  0.  ,  0.  ])

``````

You can use `set_printoptions` and a custom formatter to fix this and get a more numpy-esque printout with fewer decimal places:

``````>>> np.set_printoptions(formatter={'float': "{0:0.2e}".format})
>>> print(arr)
[2.92e+00 -1.57e-03 4.82e-08 1.93e-12]
``````

This way, you get the full versatility of `format` and maintain the full precision of numpy's datatypes.

Also note that this only affects printing, not the actual precision of the stored values used for computation.