1

Why isn't it possible to directly convert a floating point number represented as a string in Python to an int variable?

For example,

>>> val=str(10.20)
>>> int(val)
Traceback (most recent call last):
  File "<stdin>", line 1, in
ValueError: invalid literal for int() with base 10: '10.2'

However, this works,

>>> int(float(val))
10
2
  • Thanks for the edit jonrsharpe. Commented Oct 12, 2014 at 21:49
  • Because "Explicit is better than implicit." (import this). Explicitly converting an integer to a float is very different to quietly dropping parts of a string without warning the user that it wasn't what they expected. Commented Oct 12, 2014 at 21:49

2 Answers 2

1

The reason is that int is doing two different things in your two examples.

In your first example, int is converting a string to an integer. When you give it 10.2, that is not an integer so it fails.

In your second example, int is casting a floating point value to an integer. This is defined to truncate any fractional part before returning the integer value.

Sign up to request clarification or add additional context in comments.

Comments

0

There is a way to do this conversion if you are willing to use a third party library (full disclosure, I am the author). The fastnumbers library was written for quick conversions from string types to number types. One of the conversion functions is fast_forceint, which will convert your string to an integer, even if it has decimals.

>>> from fastnumbers import fast_forceint
>>> fast_forceint('56')
56
>>> fast_forceint('56.0')
56
>>> fast_forceint('56.07')
56

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.