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

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

    If you really want to make sure that a string contains only a number, any number (integer or floating point), and exactly a number, you cannot use parseInt()/ parseFloat(), Number(), or !isNaN() by themselves. Note that !isNaN() is actually returning true when Number() would return a number, and false when it would return NaN, so I will exclude it from the rest of the discussion.

    The problem with parseFloat() is that it will return a number if the string contains any number, even if the string doesn't contain only and exactly a number:

    parseFloat("2016-12-31")  // returns 2016
    parseFloat("1-1") // return 1
    parseFloat("1.2.3") // returns 1.2
    

    The problem with Number() is that it will return a number in cases where the passed value is not a number at all!

    Number("") // returns 0
    Number(" ") // returns 0
    Number(" \u00A0   \t\n\r") // returns 0
    

    The problem with rolling your own regex is that unless you create the exact regex for matching a floating point number as Javascript recognizes it you are going to miss cases or recognize cases where you shouldn't. And even if you can roll your own regex, why? There are simpler built-in ways to do it.

    However, it turns out that Number() (and isNaN()) does the right thing for every case where parseFloat() returns a number when it shouldn't, and vice versa. So to find out if a string is really exactly and only a number, call both functions and see if they both return true:

    function isNumber(str) {
      if (typeof str != "string") return false // we only process strings!
      // could also coerce to string: str = ""+str
      return !isNaN(str) && !isNaN(parseFloat(str))
    }
    

提交回复
热议问题