Check if a variable contains a numerical value in Javascript?

后端 未结 9 1438
伪装坚强ぢ
伪装坚强ぢ 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条回答
  • 2020-12-01 19:30

    This checks for numerical values, including negative and floating point numbers.

    function is_numeric(val){
        return val && /^-?\d+(\.\d+)?$/.test(val + '');
    }
    

    @Vordreller: I corrected the Regex. It should work properly now.

    0 讨论(0)
  • 2020-12-01 19:31

    I don't think any of the suggestions till now actually work. Eg

    !isNaN(parseFloat(foo))
    

    doesn't because parseFloat() ignores trailing non-numeric characters.

    To work around this, you could compare the returned value to the one returned by a cast via Number() (or equivalently by using unary +, but I prefer explicit casting):

    parseFloat(foo) === Number(foo)
    

    This will still work if both functions return NaN because NaN !== NaN is true.

    Another possibility would be to first cast to string, then to number and then check for NaN, ie

    !isNaN(Number(String(foo)))
    

    or equivalently, but less readable (but most likely faster)

    !isNaN(+('' + foo))
    

    If you want to exclude infinity values, use isFinite() instead of !isNaN(), ie

    isFinite(Number(String(foo)))
    

    The explicit cast via Number() is actually unnecessary, because isNan() and isFinite() cast to number implicitly - that's the reason why !isNaN() doesn't work!

    In my opinion, the most appropriate solution therefore would be

    isFinite(String(foo))
    

    As Matthew pointed out, the second approach does not handle strings that only contain whitespace correctly.

    It's not hard to fix - use the code from Matthew's comment or

    isFinite(String(foo).trim() || NaN)
    

    You'll have to decide if that's still nicer than comparing the results of parseFloat() and Number().

    0 讨论(0)
  • 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));
    }
    
    0 讨论(0)
提交回复
热议问题