Python中检查浮点数是否是整数
使用 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
第一个示例使用 float.is_integer() 方法检查浮点数是否为整数。
float.is_integer 方法返回一个布尔结果:
- 如果浮点数是有限的整数,则为真
- 如果不是,则为假
print((3.00).is_integer()) # ?️ True
print((3.14).is_integer()) # ?️ False
或者,我们可以使用模运算符。
使用模数检查浮点数是否为整数
检查浮点数是否为整数:
- 使用模运算符将浮点数除以 1。
- 如果除法的余数为 0,则该数为整数。
- 如果余数不为 0,则该数字有小数点。
num = 5.00
result = num % 1 == 0
print(result) # ?️ True
模 % 运算符返回第一个值除以第二个值的余数。
print(10 % 1) # ?️ 0
print(10.5 % 1) # ?️ 0.5
如果我们将数字除以 1 得到的余数是 0,那么我们就有一个整数。
相反,如果除以 1 有余数,则该数字有小数点。
或者,我们可以使用 math.floor() 方法。
使用 math.floor() 检查浮点数是否为整数
检查浮点数是否为整数:
- 将数字传递给 math.floor() 方法。
- math.floor() 方法会将数字向下舍入。
- 将四舍五入的数字与数字本身进行比较。
import math
num = 7.00
result = math.floor(num) == num
print(result) # ?️ True
math.floor() 方法返回小于或等于所提供数字的最大整数。
print(math.floor(3.99)) # ?️ 3
print(math.floor(3.00)) # ?️ 3
如果四舍五入的数字等于数字本身,那么我们就有一个整数。
如果四舍五入的数字不同,则该数字有小数点。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。