如何检查数值是否为整数? [英] How to check if a numeric value is an integer?

查看:70
本文介绍了如何检查数值是否为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一个值是否是 Python 中的整数.请注意,整数是指像 21.0-4.0000 这样的值,而 0.4-2.3 不是整数.

I need to check if a value is an integer in Python. Note that by integer I mean values like 2, 1.0 and -4.0000, whereas 0.4 and -2.3 are not integers.

我该怎么做?

推荐答案

float 实例有一个 is_integer 方法,它告诉你是否 f == int(f).因此,以下代码段适用于整数和浮点数,以及表示这两种数字类型之一的任何字符串:

float instances have an is_integer method, which tells you whether f == int(f). The following snippet will therefore work for both integers and floats, as well as any strings representing either of those numerical types:

float(value).is_integer()

这篇关于如何检查数值是否为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆