NumPy Print 2 Decimal Places: A Step Guide – NumPy Tutorial

By | December 22, 2021

In this tutorial, we will introduce how to print 2 decimal places in numpy, there are two methods.

Method 1: Use numpy.set_printpoints() function

This function can determine the way floating point numbers, arrays and other NumPy objects are displayed.

For example:

import numpy as np

a = np.random.random((3,3))
print(a)

You will see:

[[0.4222134  0.9784961  0.60628507]
 [0.56203917 0.17999193 0.21623986]
 [0.70388455 0.75263691 0.18140096]]

We can use np.set_printoptions(precision = 2) to print 2 decimal places.

a = np.random.random((3,3))
np.set_printoptions(precision = 2)
print(a)

Run this code, you will get:

[[0.06 0.17 0.04]
 [0.25 0.8  0.88]
 [0.43 0.79 0.31]]

Method 2: Use numpy.around() function

This function can round to the given number of decimals.

For example:

a = np.random.random((3,3))
print(a)
a = np.around(a, 2)
print(a)

Run this code, we can see:

[[0.50392871 0.92229656 0.15891422]
 [0.06250561 0.05533973 0.80937645]
 [0.86911354 0.24939669 0.93107257]]
[[0.5  0.92 0.16]
 [0.06 0.06 0.81]
 [0.87 0.25 0.93]]

Moreover, if you want to know how to format a float number to 2 decimal places, you can view this tutorial:

Format Python Float to 2 Decimal Places: A Step Guide – Python Tutorial