-1

I have created a function that checks if the argument that is passed is an integer or a float. But for some reason it keeps on returning true when I pass in a string. I don't understand how this happening??

If anyone can help me figure this out I would really appreciate it

function isNumeric(val){

    var patt =  new RegExp('^[0-9]+$');

    return (patt.test(val) || Math.floor(val) !== val);



}


console.log(isNumeric("Hello")); //Returns true??
json2021
  • 2,146
  • 2
  • 14
  • 28
  • `Math.floor(val) !== val` results in `NaN !== "Hello"` which is `true`; with the correct result from `patt.test(val)` (`false`) you get `return false || true;` which is `true`. – Sebastian Simon Jul 08 '16 at 21:35

2 Answers2

0

Additionally, you can reference the fiddle below. The regex pattern is successful, but the Math.floor() evaluation is problematic.

https://jsfiddle.net/joedonahue/8uw0cr4y/1/

function isNumeric(val){
    var patt =  new RegExp('^[0-9]+$');
    return (patt.test(val));
    //return Math.floor(val) !== val;
}
alert(isNumeric("Hello")); //Returns true??
atjoedonahue
  • 476
  • 6
  • 19
0

When you pass in a string, you have the following expression:

patt.test("Hello") || Math.floor("Hello") !== "Hello"

which then becomes:

false || NaN !== "Hello"

which then becomes:

false || true

Since || returns a truthy value if either of its arguments is truthy, this returns true.

See Is there a (built-in) way in JavaScript to check if a string is a valid number? for how to perform your check properly.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612