0

I am new to python and when I am trying to print the value of list which hold the float value and strings are printing more zeroes in float values. why this behavior in python can anyone please explain.

list = ['abcd', 786 , 2.23, 'john', 7.23 ,'Deepak','Umesh']
#tinylist = [123, 'john']
print list # Prints complete list 

o/p

['abcd', 786, 2.23, 'john', 7.2300000000000004, 'Deepak', 'Umesh']

why so many zeroes are coming after 7.23

nbro
  • 15,395
  • 32
  • 113
  • 196
Amit Kumar
  • 83
  • 1
  • 13

1 Answers1

1

Python, like any programming language, can't represent all floating-point values exactly; sometimes precision problems will cause issues like you see. For any calculation, 7.2300000000000004 is so close to 7.23 that it shouldn't matter.

Resources to learn more: https://docs.python.org/2/tutorial/floatingpoint.html http://floating-point-gui.de/

Also, it's better not to use list as a variable name, because that shadows a built-in.

perigon
  • 2,160
  • 11
  • 16
  • I'm sure sure this is a floating point issue, but the actual original code snippet does not produce that output, at least in Python 2.7 on my system – Chris_Rands Jul 31 '17 at 09:51
  • @Chris_Rands is it possible that the output depends on hardware/OS/etc.? Also, maybe OP is using a seriously old version of Python... – perigon Jul 31 '17 at 09:53
  • @AmitKumar if you're using a version of Python earlier than 2.7, update. In the meantime, learn about the ```format``` method to control how your output looks. – perigon Jul 31 '17 at 09:54
  • @perigon Thanks for your comment. – Amit Kumar Jul 31 '17 at 10:02