(Built-in) way in JavaScript to check if a string is a valid number

前端 未结 30 3344
-上瘾入骨i
-上瘾入骨i 2020-11-22 01:54

I\'m hoping there\'s something in the same conceptual space as the old VB6 IsNumeric() function?

相关标签:
30条回答
  • 2020-11-22 02:28

    If anyone ever gets this far down, I spent some time hacking on this trying to patch moment.js (https://github.com/moment/moment). Here's something that I took away from it:

    function isNumeric(val) {
        var _val = +val;
        return (val !== val + 1) //infinity check
            && (_val === +val) //Cute coercion check
            && (typeof val !== 'object') //Array/object check
    }
    

    Handles the following cases:

    True! :

    isNumeric("1"))
    isNumeric(1e10))
    isNumeric(1E10))
    isNumeric(+"6e4"))
    isNumeric("1.2222"))
    isNumeric("-1.2222"))
    isNumeric("-1.222200000000000000"))
    isNumeric("1.222200000000000000"))
    isNumeric(1))
    isNumeric(0))
    isNumeric(-0))
    isNumeric(1010010293029))
    isNumeric(1.100393830000))
    isNumeric(Math.LN2))
    isNumeric(Math.PI))
    isNumeric(5e10))
    

    False! :

    isNumeric(NaN))
    isNumeric(Infinity))
    isNumeric(-Infinity))
    isNumeric())
    isNumeric(undefined))
    isNumeric('[1,2,3]'))
    isNumeric({a:1,b:2}))
    isNumeric(null))
    isNumeric([1]))
    isNumeric(new Date()))
    

    Ironically, the one I am struggling with the most:

    isNumeric(new Number(1)) => false
    

    Any suggestions welcome. :]

    0 讨论(0)
  • 2020-11-22 02:30

    My attempt at a slightly confusing, Pherhaps not the best solution

    function isInt(a){
        return a === ""+~~a
    }
    
    
    console.log(isInt('abcd'));         // false
    console.log(isInt('123a'));         // false
    console.log(isInt('1'));            // true
    console.log(isInt('0'));            // true
    console.log(isInt('-0'));           // false
    console.log(isInt('01'));           // false
    console.log(isInt('10'));           // true
    console.log(isInt('-1234567890'));  // true
    console.log(isInt(1234));           // false
    console.log(isInt('123.4'));        // false
    console.log(isInt(''));             // false
    
    // other types then string returns false
    console.log(isInt(5));              // false
    console.log(isInt(undefined));      // false
    console.log(isInt(null));           // false
    console.log(isInt('0x1'));          // false
    console.log(isInt(Infinity));       // false
    
    0 讨论(0)
  • 2020-11-22 02:31

    Quote:

    isNaN(num) // returns true if the variable does NOT contain a valid number

    is not entirely true if you need to check for leading/trailing spaces - for example when a certain quantity of digits is required, and you need to get, say, '1111' and not ' 111' or '111 ' for perhaps a PIN input.

    Better to use:

    var num = /^\d+$/.test(num)
    
    0 讨论(0)
  • 2020-11-22 02:32

    Try the isNan function:

    The isNaN() function determines whether a value is an illegal number (Not-a-Number).

    This function returns true if the value equates to NaN. Otherwise it returns false.

    This function is different from the Number specific Number.isNaN() method.

      The global isNaN() function, converts the tested value to a Number, then tests it.

    Number.isNan() does not convert the values to a Number, and will not return true for any value that is not of the type Number...

    0 讨论(0)
  • 2020-11-22 02:33

    If you're just trying to check if a string is a whole number (no decimal places), regex is a good way to go. Other methods such as isNaN are too complicated for something so simple.

        function isNumeric(value) {
            return /^-?\d+$/.test(value);
        }
        
        console.log(isNumeric('abcd'));         // false
        console.log(isNumeric('123a'));         // false
        console.log(isNumeric('1'));            // true
        console.log(isNumeric('1234567890'));   // true
        console.log(isNumeric('-23'));          // true
        console.log(isNumeric(1234));           // true
        console.log(isNumeric('123.4'));        // false
        console.log(isNumeric(''));             // false
        console.log(isNumeric(undefined));      // false
        console.log(isNumeric(null));           // false
    

    To only allow positive whole numbers use this:

        function isNumeric(value) {
            return /^\d+$/.test(value);
        }
    
        console.log(isNumeric('123'));          // true
        console.log(isNumeric('-23'));          // false
    
    0 讨论(0)
  • 2020-11-22 02:35

    The accepted answer for this question has quite a few flaws (as highlighted by couple of other users). This is one of the easiest & proven way to approach it in javascript:

    function isNumeric(n) {
      return !isNaN(parseFloat(n)) && isFinite(n);
    }
    

    Below are some good test cases:

    console.log(isNumeric(12345678912345678912)); // true
    console.log(isNumeric('2 '));                 // true
    console.log(isNumeric('-32.2 '));             // true
    console.log(isNumeric(-32.2));                // true
    console.log(isNumeric(undefined));            // false
    
    // the accepted answer fails at these tests:
    console.log(isNumeric(''));                   // false
    console.log(isNumeric(null));                 // false
    console.log(isNumeric([]));                   // false
    
    0 讨论(0)
提交回复
热议问题