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?

6
  • 1
    floating-point-gui.de Commented Mar 23, 2020 at 14:34
  • 0.30000000000000004.com Commented Mar 23, 2020 at 14:35
  • 2
    Does this answer your question? How to pretty-print a numpy.array without scientific notation and with given precision? Commented Mar 23, 2020 at 14:36
  • haha I can't help but laugh that this a question asked by many other programming newbs. Cheers guys! Commented Mar 23, 2020 at 14:44
  • 1
    yep, I was trying to accept your answer below but was prompted to wait 4 minutes before doing so. Commented Mar 23, 2020 at 15:02

3 Answers 3

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]
Sign up to request clarification or add additional context in comments.

Comments

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']

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.