Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

ufunc Rounding Decimals

Rounding Decimals

In NumPy, there are five primary methods for rounding off decimals:

  • truncation
  • fix
  • rounding
  • floor
  • ceil

Truncation

Eliminate the decimals and return the floating-point number closest to zero by using the trunc() and fix() functions.

Example

Truncate the elements of the following array:

import numpy as np

arr = np.trunc([-3.16663.6667])

print(arr)

Example

Using the fix() function with the same example:

import numpy as np

arr = np.fix([-3.16663.6667])

print(arr)

Rounding

The around() function increments the preceding digit or decimal by 1 if it is greater than or equal to 5; otherwise, it leaves it unchanged.

For example, rounding 3.166663.16666 to one decimal place results in 3.23.2.

Example

Round 3.16663.1666 to two decimal places:

import numpy as np

arr = np.around(3.16662)

print(arr)