Check if Number Is Integer JavaScript | Number.isInteger

Number.isInteger()

Метод Number.isInteger() определяет, является ли переданное значение целым числом.

Try it

Syntax

Parameters

Значение,которое будет проверено на целое число.

Return value

Логическое значение true , если заданное значение является целым числом. В противном случае false .

Description

Если целевое значение является целым числом, верните true , иначе верните false . Если значение равно NaN или Infinity , верните false . Метод также возвращает значение true для чисел с плавающей запятой, которые могут быть представлены как целые числа. Он всегда будет возвращать false , если значение не является числом ( typeof value !== «number» ).

Обратите внимание, что некоторые числовые литералы, хотя и выглядят как нецелые числа, на самом деле представляют целые числа — из-за предела точности кодирования чисел с плавающей запятой ECMAScript (IEEE-754). Например, 5.0000000000000001 отличается от 5 только на 1e-16 , что слишком мало для представления. (Для справки, Number.EPSILON хранит расстояние между 1 и следующим представимым числом с плавающей запятой, большим 1, и это примерно 2.22e-16 .) Таким образом, 5.0000000000000001 будет представлено тем же кодированием, что и 5 , что делает Number.isInteger(5.0000000000000001) возвращает true .

Читайте также:  Vue cli css module

В аналогичном смысле числа с величиной, близкой к Number.MAX_SAFE_INTEGER , будут страдать от потери точности и заставят Number.isInteger возвращать true , даже если это не целое число. (Фактическое пороговое значение зависит от того, сколько битов необходимо для представления десятичного числа — например, Number.isInteger(4500000000000000.1) равно true , а Number.isInteger(4500000000000000.5) равно false .)

Examples

Using isInteger

Number.isInteger(0); // true Number.isInteger(1); // true Number.isInteger(-100000); // true Number.isInteger(99999999999999999999999); // true Number.isInteger(0.1); // false Number.isInteger(Math.PI); // false Number.isInteger(NaN); // false Number.isInteger(Infinity); // false Number.isInteger(-Infinity); // false Number.isInteger('10'); // false Number.isInteger(true); // false Number.isInteger(false); // false Number.isInteger([1]); // false Number.isInteger(5.0); // true Number.isInteger(5.000000000000001); // false Number.isInteger(5.0000000000000001); //истинно,из-за потери точности Number.isInteger(4500000000000000.1); //истинно,из-за потери точности 

Specifications

Источник

Number.isInteger()

The Number.isInteger() static method determines whether the passed value is an integer.

Try it

Syntax

Parameters

The value to be tested for being an integer.

Return value

The boolean value true if the given value is an integer. Otherwise false .

Description

If the target value is an integer, return true , otherwise return false . If the value is NaN or Infinity , return false . The method will also return true for floating point numbers that can be represented as integer. It will always return false if the value is not a number.

Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, 5.0000000000000001 only differs from 5 by 1e-16 , which is too small to be represented. (For reference, Number.EPSILON stores the distance between 1 and the next representable floating-point number greater than 1, and that is about 2.22e-16 .) Therefore, 5.0000000000000001 will be represented with the same encoding as 5 , thus making Number.isInteger(5.0000000000000001) return true .

In a similar sense, numbers around the magnitude of Number.MAX_SAFE_INTEGER will suffer from loss of precision and make Number.isInteger return true even when it’s not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, Number.isInteger(4500000000000000.1) is true , but Number.isInteger(4500000000000000.5) is false .)

Examples

Using isInteger

.isInteger(0); // true Number.isInteger(1); // true Number.isInteger(-100000); // true Number.isInteger(99999999999999999999999); // true Number.isInteger(0.1); // false Number.isInteger(Math.PI); // false Number.isInteger(NaN); // false Number.isInteger(Infinity); // false Number.isInteger(-Infinity); // false Number.isInteger("10"); // false Number.isInteger(true); // false Number.isInteger(false); // false Number.isInteger([1]); // false Number.isInteger(5.0); // true Number.isInteger(5.000000000000001); // false Number.isInteger(5.0000000000000001); // true, because of loss of precision Number.isInteger(4500000000000000.1); // true, because of loss of precision 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Feb 21, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Check if Number Is Integer JavaScript|Number.isInteger

JavaScript check if number is integer; In this tutorial, you will learn how to check if number is integer in javaScript.

When you work with javascript. Most times you check that value is string, number, integer number, decimal number, etc. So In this tutorial, you will learn how you can check value is a number or not in javascript using the number.isInteger() method.

Check if Number Is Integer JavaScript|Number.isInteger

You can easily check if a number is an integer or not in javascript using the number.isInteger() function.

JavaScript Number.isInteger() Method

In JavaScript Number.isInteger() method works with numbers, it will check whether a value an integer. This method returns true if the value is of the type Number and an integer. Otherwise, it will return false.

If the target value is an integer, return true, otherwise, return false. If the value is NaN or Infinity, return false. The method will also return true for floating-point numbers that can be represented as an integer.

Syntax

The syntax of number.isInterger() method is:

Parameters

This method accept only one parameter.

Example of the Number.isInterger()

You can use this below source code to check a given number is an integer or not in javascript.

We will use javascript number method, The Number() the method converts a string to a number.

   

How to Check if Number Is Integer or Not In JavaScript





Demo

How to Check if Number Is Integer or Not In JavaScript

Conclusion

In this javascript tutorial of the Number.isInteger() method, you have learned how you can check a number is an integer or not in javascript using the is Number.isInteger() method. In javaScript Number.isInteger() function to check whether the value passed to it is an integer or not. It returns true if the passed value is an integer, otherwise, it will return false.

If you have any questions or thoughts to share, use the comment form below to reach us.

Author Admin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Источник

JavaScript Number isInteger()

The Number.isInteger() method returns true if a value is an integer of the datatype Number.

Otherwise it returns false .

See Also:

Syntax

Parameters

Return Value

More Examples

Number.isInteger(0);
Number.isInteger(0/0);
Number.isInteger(0.5);
Number.isInteger(false);
Number.isInteger(NaN);
Number.isInteger(Infinity);
Number.isInteger(-Infinity);

Browser Support

Number.isInteger() is an ECMAScript6 (ES6) feature.

ES6 (JavaScript 2015) is supported in all modern browsers:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

Number.isInteger() is not supported in Internet Explorer 11 (or earlier).

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

JavaScript/TypeScript – Check if Variable is a Number

Learn to check if a given variable’s value is a number or not, using different solutions such as Number.isFinite() and typeof() functions. The given solutions work with JavaScript as well as TypeScript.

1. Using JavaScript Number object

1.1. Checking a Number with Number.isFinite()

The Number class is part of ES6, so it is also available in TypeScript. The Number.isFinite() determines whether the passed value is a finite number i.e. value is neither positive Infinity, negative Infinity, nor NaN.

Number.isFinite() Also checks for other edge cases such as null, undefined and empty strings.

Number.isFinite(0); //true Number.isFinite(100); //true Number.isFinite(-100); //true Number.isFinite(100.12); //true Number.isFinite(-100.12); //true Number.isFinite(''); //false Number.isFinite('100'); //false Number.isFinite(null); //false Number.isFinite(undefined); //false Number.isFinite(0 / 0); //false Number.isFinite(Infinity); //false Number.isFinite(-Infinity); //false Number.isFinite(NaN); //false Number.isFinite(true); //false Number.isFinite(false); //false

1.2. Checking an Integer with Number.isInteger()

Note that if we strictly check for integer types, we can use the Number.isInteger() function that determines whether the passed value is an integer.

Also, notice that if the value has a fraction part as .00 , it will also be considered an integer value. For other edge cases, such as null, undefined etc., the result will be similar to Number.isFinite() function.

Number.isInteger(0); //true Number.isInteger(100); //true Number.isInteger(-100); //true Number.isInteger(100.00); //true - Needs special attention Number.isInteger(100.12); //false Number.isInteger('100'); //false //Other edge cases are similar to Number.isFinite()

1.3. Parsing a String to Number with Number.parseFloat()

In some cases, we get the value as string from the API response and want to validate if the value is a valid number. In this case, we can use Number.parseFloat() parses an argument and returns a floating point number.

If an argument cannot be parsed, it returns NaN.

Number.parseFloat(0); //0 Number.parseFloat(10); //10 Number.parseFloat(-10); //-10 Number.parseFloat(10.00); //10 Number.parseFloat(10.12); //10.12 Number.parseFloat('0'); //0 Number.parseFloat('10'); //10 Number.parseFloat('-10'); //-10 Number.parseFloat('10.00'); //10 Number.parseFloat('10.12'); //10.12 //For other cases it returns NaN Number.isFinite(''); //NaN Number.isFinite(null); //NaN Number.isFinite(undefined); //NaN

The typeof() function is used to find the data type of a JavaScript variable. If typeof function returns the type as ‘number’ for number and integer values.

We need to put special checks in the code for NaN, positive Infinity and negative Infinity because these all are of type number.

typeof(0) //number typeof(10) //number typeof(-10) //number typeof(10.12) //number typeof(-10.12) //number //Special checks needed for these constants typeof(NaN) //number typeof(Infinity) //number typeof(-Infinity) //number

In this ES6 tutorial, we learned to check if a given variable is a number or not in JavaScript and TypeScript. We learned to check for the edge cases including empty strings, null, undefined and NaN values.

Using the Number.isFinite() is the recommended approach because if returns the most appropriate values in all normal and edge cases.

Источник

Оцените статью