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

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

    I recently wrote an article about ways to ensure a variable is a valid number: https://github.com/jehugaleahsa/artifacts/blob/master/2018/typescript_num_hack.md The article explains how to ensure floating point or integer, if that's important (+x vs ~~x).

    The article assumes the variable is a string or a number to begin with and trim is available/polyfilled. It wouldn't be hard to extend it to handle other types, as well. Here's the meat of it:

    // Check for a valid float
    if (x == null
        || ("" + x).trim() === ""
        || isNaN(+x)) {
        return false;  // not a float
    }
    
    // Check for a valid integer
    if (x == null
        || ("" + x).trim() === ""
        || ~~x !== +x) {
        return false;  // not an integer
    }
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题