为什么 1e400 不是一个整数?
why is 1e400 not an int?
为什么科学记数法中的数字总是读作 float
,以及如何将像 '1e400' 这样的字符串转换为 int
(对于 float
) ?
>>>int('1e400')
ValueError: invalid literal for int() with base 10: '1e400'
>>>int(float('1e400'))
OverflowError: cannot convert float infinity to integer
我知道,我可以做一个像这样的函数:
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`
但这不是一个非常pythonic的方式,有没有更好的方式?
也许您可以在转换为 int 之前使用 Decimal
作为中间类型。
>>> import decimal
>>> decimal.Decimal("1e400")
Decimal('1E+400')
>>> int(decimal.Decimal("1e400"))
10000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
0
为什么科学记数法中的数字总是读作 float
,以及如何将像 '1e400' 这样的字符串转换为 int
(对于 float
) ?
>>>int('1e400')
ValueError: invalid literal for int() with base 10: '1e400'
>>>int(float('1e400'))
OverflowError: cannot convert float infinity to integer
我知道,我可以做一个像这样的函数:
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`
但这不是一个非常pythonic的方式,有没有更好的方式?
也许您可以在转换为 int 之前使用 Decimal
作为中间类型。
>>> import decimal
>>> decimal.Decimal("1e400")
Decimal('1E+400')
>>> int(decimal.Decimal("1e400"))
10000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000
0