在 Python 中将浮点数打印到小数点后两位
Print a float to 2 decimal places in Python
使用该round()
函数将浮点数打印到小数点后两位,例如
print(round(my_float, 2))
. 该round()
函数会将浮点数四舍五入到小数点后两位并返回结果。
my_float = 4.546588367 # ✅ Print float number rounded to 2 decimals (round()) result = round(my_float, 2) print(result) # 👉️ 4.55 # --------------------------------------- # ✅ Print float number rounded to 2 decimals (f-string) result = f'{my_float:.2f}' print(result) # 👉️ '4.55' # --------------------------------------- # ✅ Print list of floats with 2 decimal places list_of_floats = [1.42342365, 3.438834, 5.5843854] result = [f'{item:.2f}' for item in list_of_floats] print(result) # 👉️ ['1.42', '3.44', '5.58']
第一个示例使用round()
函数将浮点数打印到小数点后两位。
my_float = 4.546588367 result = round(my_float, 2) print(result) # 👉️ 4.55
round函数采用以下 2 个参数:
姓名 | 描述 |
---|---|
number |
要舍入到ndigits 小数点后精度的数字 |
ndigits |
小数点后的位数,运算后的数字应该有(可选) |
该round
函数返回四舍五入到ndigits
小数点后的精度的数字。
或者,您可以使用格式化的字符串文字。
使用 f-string 将浮点数打印到小数点后两位
使用格式化的字符串文字将浮点数打印到小数点后两位,例如
print(f'{my_float:.2f}')
. 您可以在格式化字符串文字中使用表达式将浮点数打印到小数点后两位。
my_float = 4.546588367 result = f'{my_float:.2f}' print(result) # 👉️ '4.55' # --------------------------------------- number_of_decimals = 2 result = f'The result is: {my_float:.{number_of_decimals}f}' print(result) # 👉️ 'The result is: 4.55'
f
.确保将表达式括在大括号 –{expression}
中。
格式化字符串文字还使我们能够
在表达式块中使用格式特定的迷你语言。
my_float = 4.546588367 print(f'{my_float:.2f}') # 👉️ 4.55 print(f'{my_float:.3f}') # 👉️ 4.547
The digit after the period is the number of decimal places the float should
have.
If you have the number of decimal places stored in a variable, wrap it in curly
braces in the f-string.
my_float = 4.546588367 number_of_decimals = 2 result = f'The result is: {my_float:.{number_of_decimals}f}' print(result) # 👉️ 'The result is: 4.55'
If you need to print a list of floating-point numbers to 2 decimal places, use a
list comprehension.
my_float = 4.546588367 list_of_floats = [1.42342365, 3.438834, 5.5843854] result = [f'{item:.2f}' for item in list_of_floats] print(result) # 👉️ ['1.42', '3.44', '5.58']
We used a list comprehension to iterate over the list of floating-point numbers.
On each iteration, we use a formatted string literal to format the current float
to 2 decimal places and return the result.