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

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

    Maybe there are one or two people coming across this question who need a much stricter check than usual (like I did). In that case, this might be useful:

    if(str === String(Number(str))) {
      // it's a "perfectly formatted" number
    }
    

    Beware! This will reject strings like .1, 40.000, 080, 00.1. It's very picky - the string must match the "most minimal perfect form" of the number for this test to pass.

    It uses the String and Number constructor to cast the string to a number and back again and thus checks if the JavaScript engine's "perfect minimal form" (the one it got converted to with the initial Number constructor) matches the original string.

提交回复
热议问题