如何检测给定数字是否为整数? [英] How to detect if a given number is an integer?

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

问题描述

如何测试变量以确定它是否包含数字,并且它是一个整数?

How can I test a variable to ascertain if it contains a number, and it is an integer?

例如

if (1.589 == integer) // false
if (2 == integer) // true

任何线索?

推荐答案

num % 1 === 0

这会将 num 转换为数字首先,所以任何可以转换为整数的值都会通过测试(例如 '42' true )。

This will convert num to type Number first, so any value which can be converted to an integer will pass the test (e.g. '42', true).

如果你想排除这些,另外检查

If you want to exclude these, additionally check for

typeof num === 'number'

您还可以使用 parseInt()这样做,即

You could also use parseInt() to do this, ie

parseInt(num) == num

用于无类型支票和

parseInt(num) === num

用于打印支票。

请注意,测试不等效:通过检查parseInt()将首先转换为 String ,所以例如 true 将无法通过支票。

Note that the tests are not equivalent: Checking via parseInt() will first convert to String, so eg true won't pass the check.

另请注意,无类型检查通过 parseInt()将手持正确的十六进制字符串,但对于八进制(即带前导零的数字字符串)将失败,因为这些字符由 parseInt()识别,但不是由 Number( )。如果需要处理带前导零的十进制字符串,则必须指定基数参数。

Also note that the untyped check via parseInt() will handle hexadecimal strings correctly, but will fail for octals (ie numeric strings with leading zero) as these are recognized by parseInt() but not by Number(). If you need to handle decimal strings with leading zeros, you'll have to specify the radix argument.

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

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