Check that variable is a number

前端 未结 10 1470
陌清茗
陌清茗 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:19

    You should use: $.isNumeric( i )

    jQuery.isNumeric API

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

    Be aware that empty string '' and ' ' will be considered as number by isNaN and isFinite.

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

    See isNan

    EDIT: Please look at what Christoph has suggested above. It makes sense to use isFinite as suggested.

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

    You should use

    simple way to check whether given value is number by using "if condition"

    function isInteger(value)      
    {       
        num=value.trim();         
        return !(value.match(/\s/g)||num==""||isNaN(num)||(typeof(value)=='number');        
    }
    

    it will return true if the value which we are passing is an integer..

    solved for     
    value=""      //false null     
    value="12"    //true only integers       
    value="a"     //false     
    value=" 12"   //false      
    value="12 "   //false         
    value=" "     //false space        
    value="$12"   //false special characters 
    value="as12"    //false
    
    0 讨论(0)
  • 2020-12-29 21:23

    The javascript function isNaN(variable) should do the trick. It returns true if the data is not a number.

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

    You should use:

    var x = 23;
    var y = 34hhj;
    
    isNaN(x); 
    isNaN(y); 
    

    It will return true if its string and false if its a number.

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