迹忆客 专注技术分享

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

在Python中将浮点数四舍五入为N个小数

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

使用 round() 函数将浮点数舍入为 N 个小数,例如 result = round(my_float, 3)。 round() 函数将 ndigits 作为其第二个参数,并将数字四舍五入到小数点后的 N 位精度。

# ✅ 将浮点数四舍五入为N个小数

my_float = 7.456789

result_1 = round(my_float, 1)
print(result_1)  # 👉️ 7.5

result_2 = round(my_float, 2)
print(result_2)  # 👉️ 7.46

result_3 = round(my_float, 3)
print(result_3)  # 👉️ 7.457

# ----------------------------------

# ✅ 打印四舍五入到 N 位小数的浮点数

my_float = 7.456789

my_str_1 = f'{my_float:.1f}'
print(my_str_1)  # 👉️ '7.5'

my_str_2 = f'{my_float:.2f}'
print(my_str_2)  # 👉️ '7.46'

my_str_3 = f'{my_float:.3f}'
print(my_str_3)  # 👉️ '7.457'

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

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

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

如果省略 ndigits,则函数返回最接近的整数。

my_float = 7.456789

print(round(my_float))  # 👉️ 7

print(round(my_float, 1))  # 👉️ 7.5

print(round(my_float, 2))  # 👉️ 7.46

print(round(my_float, 3))  # 👉️ 7.457

如果我们需要打印四舍五入到 N 个小数位的浮点数,请使用格式化的字符串文字。

my_float = 7.456789

my_str_3 = f'{my_float:.3f}'
print(my_str_3)  # 👉️ '7.457'

格式化的字符串文字(f-strings)让我们通过在字符串前面加上 f 来在字符串中包含表达式。

my_str = 'is subscribed:'

my_bool = True

result = f'{my_str} {my_bool}'

print(result)  # 👉️ is subscribed: True

确保将表达式包裹在花括号 - {expression} 中。

我们还可以在 f 字符串的表达式中使用格式规范迷你语言。

my_float = 7.456789

my_str_1 = f'{my_float:.1f}'
print(my_str_1)  # 👉️ '7.5'

my_str_2 = f'{my_float:.2f}'
print(my_str_2)  # 👉️ '7.46'

my_str_3 = f'{my_float:.3f}'
print(my_str_3)  # 👉️ '7.457'

花括号之间的 f 字符代表定点符号。

该字符将数字格式化为小数点后指定位数的十进制数。

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

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便