在Python中将浮点数四舍五入为N个小数
使用 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 字符代表定点符号。
该字符将数字格式化为小数点后指定位数的十进制数。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串