Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting Numpy Float to String results in redundant decimal points

I am trying to convert a range of float in to string in Python. When I try to convert the numpy float in to a string, I get some redundant 0’s followed by a random number in the decimal places for some floats. For eg 0.15 converted to string returns 0.15000000000000002 instead of 0.15

Any help is appreciated.

Code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import numpy as np
x = np.arange(0.05, 0.5, .05)
print(x)
for y in x:
    print(str(y))

Output

#print(x)
[0.05 0.1  0.15 0.2  0.25 0.3  0.35 0.4  0.45]

#print(str(y))
0.05
0.1
0.15000000000000002
0.2
0.25
0.3
0.35000000000000003
0.4
0.45

>Solution :

You can round the result for example:

import numpy as np
x = np.arange(0.05, 0.5, .05)
print(x)
for y in x:
    print(str(round(y, 2)))

Syntax:

round(number, digits)

  1. number: Required. The number to be rounded
  2. digits: Optional. The number of decimals to use when rounding the number. Default is 0

More Info

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading