1

I have a problem with float in Python...

I have this in a variable:

i = 9.600000000000001

And I would transform in this:

i = 9.60000

with five numbers after the decimal point and rounded.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
m.c.dev.96
  • 23
  • 1
  • 4
  • Do you want to output the float or round the value itself? For the latter, it cannot be accomplished for most values due to the nature of floats. Research on your own to know why. – too honest for this site Nov 16 '17 at 01:49

3 Answers3

9
>>> format(9.60000001,'.5f')                                                                                                            
'9.60000'
>>> 
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Wesley
  • 1,857
  • 2
  • 16
  • 30
1
from decimal import *
getcontext().prec = 6
i = 9.600000000000001
newI = Decimal(i)/1

print(newI)

returns 9.60000. However, float(newI) return 9.6, which is correct. The real question is do you want the actual value, in which case 9.60000 = 9.6, or just display 9.6 as 9.60000? In that case, the print solutions above will get you there.

Martin
  • 1,095
  • 9
  • 14
-1

You can use the second parameter in the round() function.

i = 9.600000000000001
i = round(i, 5)
print("%.5f" % i)

will return 9.60000.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SaGwa
  • 462
  • 3
  • 5