Python 如何将浮点数格式化为固定宽度
浮点数 是包含小数点的数字,也可以称为实数。默认情况下,浮点数的小数位数为6,但我们可以使用下面介绍的方法进行修改。
在本文中,我们将了解如何在Python中将浮点数格式化为给定的宽度。
第一种方法是使用format方法。我们将格式包含在一个print语句中,并使用花括号进行引用,在花括号中我们应该提到小数位数。
示例
在下面的程序中,我们将一个浮点数作为输入,并使用 format() 方法将其四舍五入到4位小数点。
num = 123.26549
print("Given floating number is")
print(num)
print("The floating number rounded up to 4 decimal points is")
print("{:12.4f}".format(num))
输出
上述示例的输出如下所示−
Given floating number is
123.26549
The floating number rounded up to 4 decimal points is
123.2655
使用%操作符
第二种方法是使用 %操作符 。它类似于格式化方法,但我们将使用%代替格式化,并且我们还将使用%代替大括号。
示例
在下面的示例中,我们输入一个浮点数,并使用 %操作符 将其四舍五入为4位小数。
num = 123.26549
print("Given floating number is")
print(num)
print("The floating number rounded up to 4 decimal points is")
print("% .4f" %num)
输出
上面示例的输出如下:
Given floating number is
123.26549
The floating number rounded up to 4 decimal points is
123.2655
使用round运算符
第三种方法是使用round运算符。我们会提及数字和小数点的位数,然后将其放入round运算符中,并返回更新后的数字作为输出。
示例
在下面的程序中,我们将一个浮点数作为输入,并使用round方法将其四舍五入为4位小数点。
num = 123.26549
print("Given floating number is")
print(num)
print("The floating number rounded up to 4 decimal points is")
print(round(num,4))
输出
上述示例的输出如下所示:
Given floating number is
123.26549
The floating number rounded up to 4 decimal points is
123.2655