1

Why does

x = int(34.43)
y = int('72')
z = float('22.43')

give x = 34, y= 72 and z = 22.43

but

x = int('10.8')

result in an error, and not x = 10

Does it have something to do with how float values are stored in memory? Any detailed explanations as to why this happens are most welcome (not how to resolve this issue). Thanks in advance

  • "Strings with decimals cannot be immediately cast to an integer because integers do not have decimals, but floats do handle decimals and can be cast to integers." [Source](https://www.kite.com/python/answers/how-to-convert-a-string-with-decimals-to-an-integer-in-python) – Sash Sinha Jan 13 '21 at 15:25
  • https://stackoverflow.com/questions/2262333/is-there-a-built-in-or-more-pythonic-way-to-try-to-parse-a-string-to-an-integer – Golden Lion Jan 13 '21 at 16:41
  • install the try parse library https://pypi.org/project/try-parse/ then check if the string can be parse as an integer – Golden Lion Jan 13 '21 at 16:44
  • you can't convert a float in a string to an int base 10 directly. You can use the type to determine if the string is int or float then cast accordingly. https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int – Golden Lion Jan 13 '21 at 16:47
  • x=round(float("10.8"),0) print(x) if your not downcasting otherwise x=int(float("10.8")) https://www.java67.com/2015/10/how-to-convert-float-to-int-in-java-example.html – Golden Lion Jan 13 '21 at 16:51

0 Answers0