迹忆客 专注技术分享

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

Python中检查浮点数是否是整数

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

使用 float.is_integer() 方法检查浮点数是否为整数,例如 result = (3.00).is_integer()。 如果浮点数是有限的整数,float.is_integer() 方法将返回 True,否则返回 False

import math

# ✅ check if float is whole number using float.is_integer()

result_1 = (3.00).is_integer()
print(result_1)  # 👉️ True

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

# ✅ check if float is whole number using modulo

num = 5.00

result_2 = num % 1 == 0
print(result_2)  # 👉️ True

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

# ✅ check if float is whole number using math.floor()

num = 7.00

result_3 = math.floor(num) == num
print(result_3)  # 👉️ True

Python中检查浮点数是否是整数

第一个示例使用 float.is_integer() 方法检查浮点数是否为整数。

float.is_integer 方法返回一个布尔结果:

  1. 如果浮点数是有限的整数,则为真
  2. 如果不是,则为假
print((3.00).is_integer())  # 👉️ True
print((3.14).is_integer())  # 👉️ False

或者,我们可以使用模运算符。


使用模数检查浮点数是否为整数

检查浮点数是否为整数:

  1. 使用模运算符将浮点数除以 1。
  2. 如果除法的余数为 0,则该数为整数。
  3. 如果余数不为 0,则该数字有小数点。
num = 5.00

result = num % 1 == 0
print(result)  # 👉️ True

Python 使用模运算符检查浮点数是否为整数

% 运算符返回第一个值除以第二个值的余数。

print(10 % 1)  # 👉️ 0

print(10.5 % 1)  # 👉️ 0.5

如果我们将数字除以 1 得到的余数是 0,那么我们就有一个整数。

相反,如果除以 1 有余数,则该数字有小数点。

或者,我们可以使用 math.floor() 方法。


使用 math.floor() 检查浮点数是否为整数

检查浮点数是否为整数:

  1. 将数字传递给 math.floor() 方法。
  2. math.floor() 方法会将数字向下舍入。
  3. 将四舍五入的数字与数字本身进行比较。
import math


num = 7.00

result = math.floor(num) == num
print(result)  # 👉️ True

Python 使用 math.floor() 检查浮点数是否为整数

math.floor() 方法返回小于或等于所提供数字的最大整数。

print(math.floor(3.99))  # 👉️ 3
print(math.floor(3.00))  # 👉️ 3

如果四舍五入的数字等于数字本身,那么我们就有一个整数。

如果四舍五入的数字不同,则该数字有小数点。

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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便