Check if a variable contains a numerical value in Javascript?

后端 未结 9 1473
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 18:36

In PHP, it\'s pretty easy:

is_numeric(23);//true
is_numeric(\"23\");//true
is_numeric(23.5);//true
is_numeric(true);//false

But how do I do

9条回答
  •  Happy的楠姐
    2020-12-01 19:31

    To check types in javascript you can use the typeof operator:

    js> var x = 1;
    js> typeof(x);
    number
    

    So:

    if (typeof(x) === 'number') {
       // Do something
    }
    

    If you want to coerce the value of a variable to an integer, you can use parseInt(x, 10) which will parse the value as an integer in base 10. Similarly, you can use parseFloat if you want a floating point value. However, these will always coerce regardless of type so passing null, true, etc will always return a number. However, you can check whether its a valid number by calling isNaN.

    So, putting it all together:

    !isNaN(parseFloat(23)) // true
    !isNaN(parseFloat('23')) // true
    !isNaN(parseFloat(23.5)) // true
    !isNaN(parseFloat(true)) // false
    

    or

    function isNumber(x) {
        return !isNaN(parseFloat(x));
    }
    

提交回复
热议问题