Number.isInteger()
Метод Number.isInteger() определяет, является ли переданное значение целым числом.
Интерактивный пример
Синтаксис
Параметры
Значение, проверяемое на целочисленность.
Возвращаемое значение
Boolean сообщающий о том, является ли переданное значение целочисленным числом.
Описание
Если целевое значение является целым числом, возвращает true . Если значение NaN или Infinity , то возвращает false . Метод также возвращает true , если это вещественное число с точкой, которое может быть представлено в целочисленном виде.
Определить, является ли число целым числом в JavaScript
В этом посте мы обсудим, как определить, является ли число целым числом с помощью JavaScript.
1. Использование Number.isInteger() метод
Нативный JavaScript Number.isInteger() Метод определяет, является ли предоставленное значение целым числом или нет.
Обратите внимание, что этот метод возвращает false для NaN или же Infinity и возвращает true для чисел с плавающей запятой, которые могут быть представлены как целое число. например, 10.0 .
Проверка на целое число
Как в JavaScript проверить является ли число целым или дробью. Метод isInteger для проверки целостности числа. Синтаксис метода isInteger с примерами.
Чтобы узнать является ли значение целым числом или нет, для этого в JS есть специальный метод Number.isInteger()
В зависимости от результата он возвращает булево значение true или false .
Если значение является целым числом, метод возвращает true , в противном случае возвращает false .
Для отрицательных чисел метод работает так же как и для положительных чисел, а для нуля возвращает true
Если значение является NaN или бесконечностью — возвращает false .
Синтаксис метода isInteger:
Готовое решение для задач в которых необходимо генерировать случайные числа в заданном диапазоне, при этом чтобы эти числа были кратны какому то заданному числу.
Сборка арифметических операторов и методов чисел в JavaScript. Всё что связано с математикой в JavaScript с примерами функций и решений, собрано вместе на одной странице.
How to check if a variable is an integer in JavaScript?
How do I check if a variable is an integer in JavaScript, and throw an alert if it isn’t? I tried this, but it doesn’t work:
41 Answers 41
That depends, do you also want to cast strings as potential integers as well?
With Bitwise operations
Simple parse and check
Short-circuiting, and saving a parse operation:
Or perhaps both in one shot:
Performance
Testing reveals that the short-circuiting solution has the best performance (ops/sec).
If you fancy a shorter, obtuse form of short circuiting:
Of course, I’d suggest letting the minifier take care of that.
Use the === operator (strict equality) as below,
Number.isInteger() seems to be the way to go.
MDN has also provided the following polyfill for browsers not supporting Number.isInteger() , mainly all versions of IE.
Assuming you don’t know anything about the variable in question, you should take this approach:
To put it simply:
You could check if the number has a remainder:
Mind you, if your input could also be text and you want to check first it is not, then you can check the type first:
You can use a simple regular expression:
In ES6 2 new methods are added for Number Object.
In it Number.isInteger() method returns true if the argument is an integer, otherwise returns false.
Important Note: The method will also return true for floating point numbers that can be represented as integer. Eg: 5.0 (as it is exactly equal to 5 )
First off, NaN is a «number» (yes I know it’s weird, just roll with it), and not a «function».
You need to check both if the type of the variable is a number, and to check for integer I would use modulus.
Be careful while using
empty string (») or boolean (true or false) will return as integer. You might not want to do that
Number.isInteger(data)
build in function in the browser. Dosnt support older browsers
Alternatives:
However, Math.round() also will fail for empty string and boolean
To check if integer like poster wants:
notice + in front of data (converts string to number), and === for exact.
Here are examples:
The simplest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as a string or null is passed to the function) would be the following:
The following solution would also work, although not as elegant as the one above: