3

How to Check if a Variable is an Integer in JavaScript

 2 years ago
source link: https://masteringjs.io/tutorials/fundamentals/is-integer
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to Check if a Variable is an Integer in JavaScript

Jan 13, 2022

To check if a variable is an integer in JavaScript, use Number.isInteger(). Number.isInteger() returns true or false depending on the parameter provided.

let example = 12.1;
Number.isInteger(example); // false
example = 12;
Number.isInteger(example); // true
example = Infinity;
Number.isInteger(example); // false

Non-numeric values will return false, even if the value is an instance of the Number class.

Number.isInteger(null); // false
Number.isInteger('42'); // false
Number.isInteger(new Number(5)); // false

Remember that JavaScript can only represent up to 16 decimal places, so Number.isInteger() may return surprising results in cases where JavaScript doesn't have sufficient numeric precision to represent the output.

let example = 5 + 1e-16;
Number.isInteger(example); // true

example = 5 + 5e-16;
Number.isInteger(example); // false

More Fundamentals Tutorials


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK