Python 内建函数 - float([x])

Python的float()函数用于将数字或字符串转换为浮点数。它可以处理十进制数、NaN、无穷大等,并遵循特定的语法格式。当参数超出Python浮点数范围时,会引发OverflowError。如果无参数,返回0.0。该函数也可用于调用对象的float()方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Manual

Return a floating point number constructed from a number or string x.

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be ‘+’ or ‘-‘; a ‘+’ sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity. More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed:

sign           ::=  "+" | "-"
infinity       ::=  "Infinity" | "inf"
nan            ::=  "nan"
numeric_value  ::=  floatnumber | infinity | nan
numeric_string ::=  [sign] numeric_value

Here floatnumber is the form of a Python floating-point literal, described in Floating point literals. Case is not significant, so, for example, “inf”, “Inf”, “INFINITY” and “iNfINity” are all acceptable spellings for positive infinity.

Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python’s floating point precision) is returned. If the argument is outside the range of a Python float, an OverflowError will be raised.

For a general Python object x, float(x) delegates to x.float().

If no argument is given, 0.0 is returned.

Examples:

>>>
>>> float('+1.23')
1.23
>>> float('   -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf

The float type is described in Numeric Types — int, float, complex.

直译

根据给定的数字或字符串x,返回一个浮点数。
如果参数是字符串,它应该包含一个十进制数,可选填前置符号和嵌入空格。可选的符号可以是’+’或’-‘,加号对值无影响。参数可以是NaN(非数字)形式的字符串,或正负无穷。更确切的说,当移除前后空白字符后,输入必须符合以下语法:

符号           ::=  "+" | "-"
无穷大         ::=  "Infinity" | "inf"
非数字         ::=  "nan"
数字值         ::=  floatnumber | infinity | nan
数字字符串      ::=  [sign] numeric_value

这里的floatnumber是Python浮点字面形式,详情见浮点字面。无符号前提下,例如“inf”、 “Inf”、“INFINITY”和“iNfINity”是可以接受的正无穷大的拼写方式。
否则,如果参数是整数或浮点数,将返回等值的浮点数(Python的浮点精度内)。如果参数超出Python浮点范围,将会引发OverflowError。
对于常用的Python对象x,float(x)代表x.float()。
如果未给定参数,则返回0.0。
The float type is described in Numeric Types — int, float, complex.
浮点类型详细描述参考数字类型—整数、浮点数、复数

实例

>>>
>>> float('+1.23')
1.23
>>> float('   -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf

拓展阅读

浮点字面
数字类型—整数、浮点数、复数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值