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

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

    Old question, but there are several points missing in the given answers.

    Scientific notation.

    !isNaN('1e+30') is true, however in most of the cases when people ask for numbers, they do not want to match things like 1e+30.

    Large floating numbers may behave weird

    Observe (using Node.js):

    > var s = Array(16 + 1).join('9')
    undefined
    > s.length
    16
    > s
    '9999999999999999'
    > !isNaN(s)
    true
    > Number(s)
    10000000000000000
    > String(Number(s)) === s
    false
    >
    

    On the other hand:

    > var s = Array(16 + 1).join('1')
    undefined
    > String(Number(s)) === s
    true
    > var s = Array(15 + 1).join('9')
    undefined
    > String(Number(s)) === s
    true
    >
    

    So, if one expects String(Number(s)) === s, then better limit your strings to 15 digits at most (after omitting leading zeros).

    Infinity

    > typeof Infinity
    'number'
    > !isNaN('Infinity')
    true
    > isFinite('Infinity')
    false
    >
    

    Given all that, checking that the given string is a number satisfying all of the following:

    • non scientific notation
    • predictable conversion to Number and back to String
    • finite

    is not such an easy task. Here is a simple version:

      function isNonScientificNumberString(o) {
        if (!o || typeof o !== 'string') {
          // Should not be given anything but strings.
          return false;
        }
        return o.length <= 15 && o.indexOf('e+') < 0 && o.indexOf('E+') < 0 && !isNaN(o) && isFinite(o);
      }
    

    However, even this one is far from complete. Leading zeros are not handled here, but they do screw the length test.

提交回复
热议问题