Home > Enterprise >  Converting Numpy Float to String results in redundant decimal points
Converting Numpy Float to String results in redundant decimal points

Time:05-24

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

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

CodePudding user response:

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

  • Related