将科学计数法中的数字转换为 int [英] Converting number in scientific notation to int

查看:77
本文介绍了将科学计数法中的数字转换为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释一下为什么我不能使用 int() 将用科学字符串表示的整数转换成 python int 吗?

Could someone explain why I can not use int() to convert an integer number represented in string-scientific notation into a python int?

例如这不起作用:

print int('1e1')

但这确实:

print int(float('1e1'))

print int(1e1)  # Works

为什么 int 不能将字符串识别为整数?肯定就像检查指数的符号一样简单吗?

Why does int not recognise the string as an integer? Surely its as simple as checking the sign of the exponent?

推荐答案

在幕后,科学数字符号始终在内部表示为浮点数.原因是变化的数字范围,因为整数只映射到固定值范围,比如说 2^32 值.科学表示类似于具有显着性和指数的浮动表示.您可以在 https://en.wikipedia.org/wiki/Floating_point 中查找更多详细信息.

Behind the scenes a scientific number notation is always represented as a float internally. The reason is the varying number range as an integer only maps to a fixed value range, let's say 2^32 values. The scientific representation is similar to the floating representation with significant and exponent. Further details you can lookup in https://en.wikipedia.org/wiki/Floating_point.

您不能将科学数字表示形式直接转换为字符串.

You cannot cast a scientific number representation as string to integer directly.

print int(1e1)  # Works

之所以有效,是因为 1e1 作为一个数字已经是一个浮点数.

Works because 1e1 as a number is already a float.

>>> type(1e1)
<type 'float'>

回到你的问题:我们想从浮点数或科学字符串中获取一个整数.详细信息:https://docs.python.org/2/reference/lexical_analysis.html#整数

Back to your question: We want to get an integer from float or scientific string. Details: https://docs.python.org/2/reference/lexical_analysis.html#integers

>>> int("13.37")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '13.37'

对于浮点或科学表示,您必须使用 float 的中间步骤.

For float or scientific representations you have to use the intermediate step over float.

这篇关于将科学计数法中的数字转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆