在 Python 中将浮点数打印到 N 个小数位
使用格式化的字符串文字将浮点数打印到 N 个小数位,例如 print(f'{my_float:.2f}')
。 我们可以使用格式化字符串文字中的表达式将浮点数打印到 N 个小数位。
my_float = 7.3941845
# ✅ Print float rounded to 2 decimals (f-string)
result = f'{my_float:.2f}'
print(result) # 👉️ '7.39'
# ✅ Print float rounded to 3 decimals (f-string)
result = f'{my_float:.3f}'
print(result) # 👉️ '7.394'
我们使用格式化的字符串文字将浮点数打印到 N 个小数位。
格式化字符串文字
(f-strings)
让我们通过在字符串前面加上 f 来在字符串中包含表达式。
确保将表达式包裹在花括号 - {expression}
中。
格式化的字符串文字还使我们能够在表达式块中使用特定于格式的迷你语言。
my_float = 7.3941845
print(f'Result: {my_float:.2f}') # 👉️ Result: 7.39
print(f'Result: {my_float:.3f}') # 👉️ Result: 7.394
句点后面的数字是浮点数应该有的小数位数。
如果我们在变量中存储了小数位数,请将其包裹在 f 字符串中的花括号中。
my_float = 7.3941845
number_of_decimal_places = 2
result = f'{my_float:.{number_of_decimal_places}f}'
print(result) # 👉️ '7.39'
如果我们需要将浮点数列表打印到 N 个小数位,请使用列表推导。
list_of_floats = [4.2834923, 5.2389492, 9.28348243]
result = [f'{item:.2f}' for item in list_of_floats]
print(result) # 👉️ ['4.28', '5.24', '9.28']
我们使用列表推导来迭代浮点数列表。
列表推导用于对每个元素执行一些操作或选择满足条件的元素子集。 在每次迭代中,我们使用格式化的字符串文字将当前浮点数格式化为小数点后 2 位并返回结果。
或者,我们可以使用 round() 函数。
使用round()将浮点数打印到小数点后N位
使用 round()
函数将浮点数打印到 N 个小数位,例如 print(round(my_float, 2))
。 round()
函数采用浮点数和小数位数,并返回四舍五入到小数点后指定位数的数字。
my_float = 7.3941845
# ✅ Print float rounded to 2 decimals (round())
result = round(my_float, 2)
print(result) # 👉️ 7.39
# ✅ Print float rounded to 3 decimals (round())
result = round(my_float, 3)
print(result) # 👉️ 7.394
round
函数采用以下 2 个参数:
- number 小数点后四舍五入到 ndigits 精度的数字
- ndigits 小数点后的位数,运算后应有的数(可选)
round
函数返回小数点后四舍五入到 ndigits 精度的数字。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。