Converting Numpy array into list prints out extra zeros? Python

Viewed 91

I made an array using numpy, and need to convert each value into a string list.

This is the solution I found that worked :

props = np.arange(0.2,0.5,0.1)
props = [str(i) for i in props]

However when I print it out this is the result:

Out[177]: ['0.2', '0.30000000000000004', '0.4000000000000001']]

The result I want is ['0.2', '0.3', '0.4'].

What am I doing wrong?

Is there a more efficient way of doing this or is this a convulated way?

3 Answers

You can use np.around:

import numpy as np

props = np.arange(0.2,0.5,0.1)
props = np.around(props, 1)
props = [str(i) for i in props]

#output
['0.2', '0.3', '0.4']

Or:

props = np.arange(0.2,0.5,0.1)
props = [str(np.around(i, 1)) for i in props]

Just round them up

props = np.arange(0.2,0.5,0.1)
props = [str(round(i,2)) for i in props]

['0.2', '0.3', '0.4']

Beside the round()- function you can just use use this little workaround:

import numpy as np
props = np.arange(0.2,0.5,0.1)
props = [str(int(i*10)/10) for i in props]
print(props)
Related