python 浮点数转换为字符串

时间:2020-02-23 14:42:42  来源:igfitidea点击:

在本教程中,我们将看到如何将float转换为字符串。
我们可以简单地使用str方法将float转换为字符串。
让我们在简单的例子的帮助下了解。

f=1.23444432
print("Converted f to String:",str(f))

输出:

Converted f to String: 1.23444432

假设我们希望将字符串格式化为只有两个小数位。
我们可以使用以下代码来执行此操作。

f=1.23444432
#Use 5 characters, give 2 decimal places
s = "%5.2f" % f
print("Converted f to String:",s)

输出:

Converted f to String:  1.23