How to properly round numpy float arrays

2019-04-12 19:46发布

问题:

I have some sort of rounding issue when rounding floats.

x = np.array([[1.234793487329877,2.37432987432],[1.348732847,8437.328737874]])
np.round(x,2)

array([[  1.23000000e+00,   2.37000000e+00],
       [  1.35000000e+00,   8.43733000e+03]])

Is there a way to display these numbers without the zero extensions?

回答1:

Rounding floating point numbers is almost never needed (unless you want to bucket them, then your code will work just fine), if you only want to print them with less precision, use this:

print(np.array_str(x, precision=2))