Python float() 函数用法

2023-09-17 22:26:14

float()返回 float 类的一个对象,该对象表示从数字或字符串转换的浮点数。

语法:

float(x)

参数:

x:应转换的元素。

返回值:

返回浮点值。

下面的示例将数字和字符串转换为浮点数。

print("int to float: ", float(10))
print("int to float: ", float(-10))
print("string to float: ", float('10.2'))
print("string to float: ", float('-10.2'))

输出:

int to float: 10.0
int to float: -10.0
string to float: 10.2
string to float: -10.2

它还将科学浮点数转换为浮点数。

print(float(3e-002))
print(float("3e-002"))
print(float('+1E3'))

输出:

0.03 
0.03 
1000.0

下面将布尔值、nan、inf、无穷大转换为浮点数。

print("True to float: ", float(True))
print("False to float: ", float(False))
print("Nan to float: ",float('nan'))
print("Infinity to float: ",float('inf'))

输出:

True to float: 1.0
False to float: 0.0
Nan to float: nan
Infinity to float: inf

float()方法忽略空格或回车符。

print("int to float: ", float(       10))
print("string to float: ", float('      10 \n'))

输出:

int to float: 10.0 
string to float: 10.0

如果 x 不是有效的数字或数字字符串,则 float() 方法将引发 ValueError。

print(float('x'))

输出:

Traceback (most recent call last):
    print(float('x'))
ValueError: could not convert string to float: 'x'