3

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?

F Blanchet
  • 1,282
  • 3
  • 17
  • 31
apang
  • 93
  • 9
  • 1
    https://floating-point-gui.de – BlackBear Mar 23 '20 at 14:34
  • 0.30000000000000004.com – Sayandip Dutta Mar 23 '20 at 14:35
  • 2
    Does this answer your question? [How to pretty-print a numpy.array without scientific notation and with given precision?](https://stackoverflow.com/questions/2891790/how-to-pretty-print-a-numpy-array-without-scientific-notation-and-with-given-pre) – pasbi Mar 23 '20 at 14:36
  • haha I can't help but laugh that this a question asked by many other programming newbs. Cheers guys! – apang Mar 23 '20 at 14:44
  • @apang maybe you can consider accepting the answer that you found useful so that this question can be closed – Junkrat Mar 23 '20 at 14:50
  • 1
    yep, I was trying to accept your answer below but was prompted to wait 4 minutes before doing so. – apang Mar 23 '20 at 15:02

3 Answers3

1

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]
Junkrat
  • 2,754
  • 3
  • 19
  • 39
0

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']
Shahir Ansari
  • 1,438
  • 14
  • 20
0

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)
tifi90
  • 378
  • 3
  • 13