Question

I have an array array([0.79836512, 0.79700273, 0.82697546, 0.82016349, 0.79087192], dtype=float32)

and I want to keep the first two decimal points without round. So, I need an array like that,

array([0.79, 0.79, 0.82, 0.82, 0.79], dtype=float32).

Is it possible to do this with python?

Thanks

Était-ce utile?

La solution

The standard approach for truncating to two decimals is to truncate x * 100 and divide that by 100, which works for numpy arrays:

>>> np.trunc(a * 100) / 100
array([ 0.79000002,  0.79000002,  0.81999999,  0.81999999,  0.79000002], dtype=float32)

Don't be put off by the trailing non-zero digits in the output, those are just an artifact of floating-point imprecision:

>>> np.float32(.79)
0.79000002

Autres conseils

You can write a function and re-use it later:

import numpy as np
x= np.random.random(5)
x=np.array(x, dtype=np.float16)
print(x)

formatting = lambda x: "%.2f" %x

x_2dp=[]

for i in x:
    x_2dp.append(formatting(i))
    print(x_2dp)

but the answer is a string which you can convert to float.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top