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

前端 未结 30 3349
-上瘾入骨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: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
    

提交回复
热议问题