Show Sidebar Hide Sidebar

# Round

How to round the values in a NumPy array to the nearest integer.

#### New to Plotly?¶

You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

### Imports¶

This tutorial imports Numpy.

In [1]:
import numpy as np


#### Round and ARound¶

np.round() and np.around() are equivalent methods but np.around() is prefered. These methods round all values in a NumPy array according to the standard and accepted rules for rounding in scientific: for a number of the form X.5, round it up to (X+1).0 if X is odd and round down to X.0 when X is even. This is equivalent to saying:

"Round each number of the form X.5 to the nearest even number."

In [2]:
array = np.array([0.1, 2.9, 7.5, 8.5])

np.around(array)

Out[2]:
array([ 0.,  3.,  8.,  8.])
In [3]:
help(np.around)

Help on function around in module numpy.core.fromnumeric:

around(a, decimals=0, out=None)
Evenly round to the given number of decimals.

Parameters
----------
a : array_like
Input data.
decimals : int, optional
Number of decimal places to round to (default: 0).  If
decimals is negative, it specifies the number of positions to
the left of the decimal point.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output, but the type of the output
values will be cast if necessary. See doc.ufuncs (Section
"Output arguments") for details.

Returns
-------
rounded_array : ndarray
An array of the same type as a, containing the rounded values.
Unless out was specified, a new array is created.  A reference to
the result is returned.

The real and imaginary parts of complex numbers are rounded
separately.  The result of rounding a float is a float.

--------
ndarray.round : equivalent method

ceil, fix, floor, rint, trunc

Notes
-----
For values exactly halfway between rounded decimal values, Numpy
rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
-0.5 and 0.5 round to 0.0, etc. Results may also be surprising due
to the inexact representation of decimal fractions in the IEEE
floating point standard [1]_ and errors introduced when scaling
by powers of ten.

References
----------
.. [1] "Lecture Notes on the Status of  IEEE 754", William Kahan,
http://www.cs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
.. [2] "How Futile are Mindless Assessments of
Roundoff in Floating-Point Computation?", William Kahan,
http://www.cs.berkeley.edu/~wkahan/Mindless.pdf

Examples
--------
>>> np.around([0.37, 1.64])
array([ 0.,  2.])
>>> np.around([0.37, 1.64], decimals=1)
array([ 0.4,  1.6])
>>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
array([ 0.,  2.,  2.,  4.,  4.])
>>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned
array([ 1,  2,  3, 11])
>>> np.around([1,2,3,11], decimals=-1)
array([ 0,  0,  0, 10])


Still need help?