迹忆客 专注技术分享

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

在 Python 中将浮点数格式化为整数

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

使用格式化的字符串文字将浮点数格式化为整数,例如 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 方法返回小于或等于所提供数字的最大整数。

转载请发邮件至 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便