Why is 1e400 not int?

Why is the number in Scientific notation always read as a float , and how can I convert a string like "1e400" to int (which is too big 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 is not a Putin way, is there a better way?

+5
source share
1 answer

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

 >>> import decimal >>> decimal.Decimal("1e400") Decimal('1E+400') >>> int(decimal.Decimal("1e400")) 10000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000000000000000000000000000 0 
+8
source

Source: https://habr.com/ru/post/1245340/


All Articles