Python 内置函数

Python float() 函数用于把值转成浮点数

语法

float(x)

参数

x:要转换的数字或字符串。

返回值

返回浮点数 float。非法字符串抛 ValueError

示例

print(float(3))            # 3.0
print(float("2.5"))        # 2.5
print(float("1e3"))        # 1000.0,科学计数法
print(float(True))         # 1.0
print(float("3"))          # 3.0

输出:

3.0
2.5
1000.0
1.0
3.0

注意事项

float("abc") 抛 ValueError。浮点数有精度问题:0.1 + 0.2 != 0.3(比较时用近似判断)。