Home javascript Check for JS number

Check for JS number

Author

Date

Category

Made a number check function:

function isAN (value) {
 return isFinite (value) & amp; & amp; value === parseInt (value, 10);
}

Everything works, but I can’t pass one test:

new Number () s

✘ isAN (new Number (1)) – Expected: true, instead got: false

How can I add a condition for such a check to pass?

isAN (new Number (1)) // now false but want true

All tests:

Strings Test.assertEquals (isAN (“2”) , false )

Booleans Test.assertEquals (isAN (true) , false )

Others Test.assertEquals (isAN (null) , false )

Numbers Test.assertEquals (isAN (2) , true )

new Number () s Test.assertEquals (isAN (Number (1)) , true )

NaN Number () s – Test.assertEquals (isAN (NaN) , false)


Answer 1, authority 100%

Creating a primitive object with handles is primitivism.
But, since for some reason this possibility exists, do a check:

function isAN (value) {
 if (value instanceof Number)
  value = value.valueOf (); // If this is a number object, then we take the value, which will be the number
 return isFinite (value) & amp; & amp; value === parseInt (value, 10);
}
console.info (isAN (1));
console.info (isAN (new Number (1)));
console.info (isAN (null)); 

Answer 2, authority 25%

Why not use parseInt or parseFloat bindings:
if (parseInt (value) & gt; = 0 || parseInt (value) & lt; = 0)

Passes all tests.


Answer 3, authority 12%

function isAN (value) {
 return (value instanceof Number || typeof value === 'number') & amp; & amp; ! isNaN (value);
}
console.info (isAN (1));
console.info (isAN (new Number (1)));
console.info (isAN (null));
console.info (isAN ("1"));
console.info (isAN (true)); 

Answer 4, authority 12%

function isAN (value) {return + value; }


Answer 5

use without new, together with new you get a wrapper object

isAN (Number (1)) // true

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions