迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

在 Python 中将浮点数打印到 N 个小数位

作者:迹忆客 最近更新:2022/11/06 浏览次数:

使用格式化的字符串文字将浮点数打印到 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'

Python 中将浮点数打印到 N 个小数位

我们使用格式化的字符串文字将浮点数打印到 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

Python 使用round()将浮点数打印到小数点后N位

round 函数采用以下 2 个参数:

  • number 小数点后四舍五入到 ndigits 精度的数字
  • ndigits 小数点后的位数,运算后应有的数(可选)

round 函数返回小数点后四舍五入到 ndigits 精度的数字。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Python 中的 Pandas 插入方法

发布时间:2024/04/23 浏览次数:112 分类:Python

本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。

Pandas 重命名多个列

发布时间:2024/04/22 浏览次数:199 分类:Python

本教程演示了如何使用 Pandas 重命名数据框中的多个列。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便