Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is 1e400 not an int?

Why is a number in Scientific notation always read as a float, and how can i convert a string like '1e400' to an int (which is too large for a float) ?

>>>int('1e400') 
ValueError: invalid literal for int() with base 10: '1e400'
>>>int(float('1e400'))
OverflowError: cannot convert float infinity to integer

i know, i can make a function like:

def strtoint(string):
  parts = string.split('e')
  if len(parts) == 1:
    return int(string)
  elif len(parts) == 2:
    if int(parts[1])<0:
      return int(string)
    return int(parts[0])*10**int(parts[1])
  else:
    return int(string) #raise a error if the string is invalid, but if the variable string is not a string, it may have other way to convert to an `int`

But this not a very pythonic way, is there a better way?

like image 289
12431234123412341234123 Avatar asked Mar 18 '16 18:03

12431234123412341234123


People also ask

How do you convert a float to an int in Python?

A float value can be converted to an int value no larger than the input by using the math. floor() function, whereas it can also be converted to an int value which is the smallest integer greater than the input using math. ceil() function.

How do you convert int to scientific notation in Python?

int(float(1e+001)) will work.


1 Answers

Perhaps you could use Decimal as an intermediary type before converting to int.

>>> import decimal
>>> decimal.Decimal("1e400")
Decimal('1E+400')
>>> int(decimal.Decimal("1e400"))
10000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
0
like image 104
Kevin Avatar answered Oct 21 '22 23:10

Kevin