5

Is there any way to check if a long integer is too large to convert to a float in python?

1 Answer 1

13
>>> import sys
>>> sys.float_info.max
1.7976931348623157e+308

Actually, if you try to convert an integer too big to a float, an exception will be raised.

>>> float(2 * 10**308)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C double
Sign up to request clarification or add additional context in comments.

1 Comment

For pedants: if you care about edge-cases, then the second method ('try it and see') is a bit more reliable. There are integers larger than sys.float_info.max (only by a tiny amount, though) that can still safely be converted to float. On a typical machine, int(sys.float_info.max) is 2**1024 - 2**971, but integers up to and including 2**1024 - 2**970 - 1 can be converted without raising OverflowError.

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.