26

I want to truncate the float values within the numpy array, for .e.g.

2.34341232 --> 2.34 

I read the post truncate floating point but its for one float. I don't want to run a loop on the numpy array, it will be quite expensive. Is there any inbuilt method within numpy which can do this easily? I do need output as a float not string.

4
  • 1
    Numpy provides the around method. The syntax is np.around(numpy_array, num_decimals). For example: a = np.array([2.3434]), np.around(a, 2) --> produces array([2.34]). Is this what are you looking for? Commented Feb 3, 2017 at 10:28
  • this looks like a dupe: stackoverflow.com/questions/21008858/… Commented Feb 3, 2017 at 10:31
  • 1
    Do you actually want to discard the data after the 2nd decimal place, or do you just want to change how the data is displayed? If the former, use the numpy.around or numpy.round method. Commented Feb 3, 2017 at 10:37
  • @AlonAlexander num = ((num*100)//1)/100 this logic only works for positive values. For example to truncate negative value to one decimal , x = -2.134 then (-2.134*10//1)10 gives -3, which is not an acceptable answer.! Commented Apr 13, 2021 at 9:50

2 Answers 2

44

Try out this modified version of numpy.trunc().

import numpy as np
def trunc(values, decs=0):
    return np.trunc(values*10**decs)/(10**decs)

Sadly, numpy.trunc function doesn't allow decimal truncation. Luckily, multiplying the argument and dividing it's result by a power of ten give the expected results.

vec = np.array([-4.79, -0.38, -0.001, 0.011, 0.4444, 2.34341232, 6.999])

trunc(vec, decs=2)

which returns:

>>> array([-4.79, -0.38, -0.  ,  0.01,  0.44,  2.34,  6.99])
Sign up to request clarification or add additional context in comments.

1 Comment

Happy to report this seems to run in only about half the time as np.around for anyone switching their rounding -> truncating logic.
17

Use numpy.round:

import numpy as np
a = np.arange(4) ** np.pi
a
=> array([  0.        ,   1.        ,   8.82497783,  31.5442807 ])
a.round(decimals=2)
=> array([  0.  ,   1.  ,   8.82,  31.54])

3 Comments

How is this the answer when the question is for truncation, not rounding? (I know, I know, the asker accepted it. So I'm really mystified at them, even more so than this answer.)
Rounding might be subtle when not carefull. Please see my answer for real truncation.
I think this answer is not correct to the question. Casually, the third decimal is less than 5 in all array elements and for this reason the output is successful, however if you change the decimal numbers ( 'a.round(decimals=3)') to 1 or 3, it outputs 8.825, what is wrong, and if you want to truncate, it should output 8.254

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.