Check that variable is a number

前端 未结 10 1577
陌清茗
陌清茗 2020-12-29 20:38

How can I check that a variable is a number, either an integer or a string digit?

In PHP I could do:

if (is_int($var)) {
    echo \'$var is integer\'         


        
相关标签:
10条回答
  • 2020-12-29 21:27

    I'd go with

    isFinite(String(foo))
    

    See this answer for an explanation why. If you only want to accept integer values, look here.

    0 讨论(0)
  • 2020-12-29 21:29
    function isNumeric( $probe )
    {
        return parseFloat( String( $probe ) ) == $probe;
    }
    
    0 讨论(0)
  • 2020-12-29 21:34

    I'm pretty new to javascript but it seems like typeof(blah) lets you check if something is a number (it doesn't say true for strings). A know the OP asked for strings + numbers but I thought this might be worth documenting for other people.

    eg:

    function isNumeric(something){
        return typeof(something) === 'number';
    }
    

    Here are the docs

    and here's a few console runs of what typeof produces:

    typeof(12);
    "number"
    typeof(null);
    "object"
    typeof('12');
    "string"
    typeof(12.3225);
    "number"  
    

    one slight weirdness I am aware of is

    typeof(NaN);
    "number"
    

    but it wouldn't be javascript without something like that right?!

    0 讨论(0)
  • 2020-12-29 21:35

    You should use:

    if(Number.isInteger(variable))
       alert("It is an integer");
    else
       alert("It is not a integer");
    

    you can find the reference in: Number.isInteger()

    0 讨论(0)
提交回复
热议问题