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

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

    2019: Practical and tight numerical validity check

    Often, a 'valid number' means a Javascript number excluding NaN and Infinity, ie a 'finite number'.

    To check the numerical validity of a value (from an external source for example), you can define in ESlint Airbnb style :

    /**
     * Returns true if 'candidate' is a finite number or a string referring (not just 'including') a finite number
     * To keep in mind:
     *   Number(true) = 1
     *   Number('') = 0
     *   Number("   10  ") = 10
     *   !isNaN(true) = true
     *   parseFloat('10 a') = 10
     *
     * @param {?} candidate
     * @return {boolean}
     */
    function isReferringFiniteNumber(candidate) {
      if (typeof (candidate) === 'number') return Number.isFinite(candidate);
      if (typeof (candidate) === 'string') {
        return (candidate.trim() !== '') && Number.isFinite(Number(candidate));
      }
      return false;
    }
    

    and use it this way:

    if (isReferringFiniteNumber(theirValue)) {
      myCheckedValue = Number(theirValue);
    } else {
      console.warn('The provided value doesn\'t refer to a finite number');
    }
    

提交回复
热议问题