在 Python 中将浮点数格式化为整数
使用格式化的字符串文字将浮点数格式化为整数,例如 result = f'{math.trunc(my_float)}'
。 我们可以使用 f 字符串中的表达式通过截断或舍入将浮点数格式化为整数。
import math
my_float = 378.656789
# ✅ 通过删除小数部分(截断)将浮点格式格式化为 int
result = f'{math.trunc(my_float)}'
print(result) # 👉️ 378
# ----------------------------------------------
# ✅ 将浮点格式设置为带舍入的 int
result = f'{my_float:.0f}'
print(result) # 👉️ 379
# ----------------------------------------------
# ✅ 通过四舍五入将浮点格式格式化为 int
result = f'{math.ceil(378.000001)}'
print(result) # 👉️ 379
我们使用格式化的字符串文字将浮点数格式化为整数。
第一个示例使用格式化字符串文字中的 math.trunc()
方法来删除浮点数的小数部分。
import math
my_float = 378.656789
result = f'Result: {math.trunc(my_float)}'
print(result) # 👉️ Result: 378
math.trunc
方法接受一个数字,删除它的小数部分并返回它的整数部分。
math.trunc()
方法向零舍入。
import math
print(math.trunc(3.468)) # 👉️ 3
print(math.trunc(-3.468)) # 👉️ -3
格式化字符串文字(f-strings)让我们通过在字符串前面加上 f 来在字符串中包含表达式。
my_str = 'The number is:'
my_int = 123
result = f'{my_str} {my_int}'
print(result) # 👉️ The number is: 123
确保将表达式包裹在花括号 - {expression}
中。
格式化的字符串文字还使我们能够在表达式块中使用特定于格式的迷你语言。
my_float = 378.656789
result = f'{my_float:.0f}'
print(result) # 👉️ 379
句点后面的数字是数字应该有的小数位数。
注意 ,f-strings
格式带有舍入。
将浮点数格式化为整数时,可以使用 math.ceil()
方法进行四舍五入。
import math
result = f'{math.ceil(378.000001)}'
print(result) # 👉️ 379
math.ceil
方法返回大于或等于所提供数字的最小整数。
如果需要向下取整,请使用 math.floor()
方法。
import math
result = f'{math.floor(378.9999999)}'
print(result) # 👉️ 378
math.floor
方法返回小于或等于所提供数字的最大整数。
相关文章
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 日期时间。