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

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

    Well, I'm using this one I made...

    It's been working so far:

    function checkNumber(value) {
        return value % 1 == 0;
    }
    

    If you spot any problem with it, tell me, please.

    0 讨论(0)
  • 2020-11-22 02:36

    It is not valid for TypeScript as:

    declare function isNaN(number: number): boolean;

    For TypeScript you can use:

    /^\d+$/.test(key)

    0 讨论(0)
  • 2020-11-22 02:37

    In my application we are only allowing a-z A-Z and 0-9 characters. I found the answer above using " string % 1 === 0" worked unless the string began with 0xnn (like 0x10) and then it would return it as numeric when we didn't want it to. The following simple trap in my numeric check seems to do the trick in our specific cases.

    function isStringNumeric(str_input){   
        //concat a temporary 1 during the modulus to keep a beginning hex switch combination from messing us up   
        //very simple and as long as special characters (non a-z A-Z 0-9) are trapped it is fine   
        return '1'.concat(str_input) % 1 === 0;}
    

    Warning : This might be exploiting a longstanding bug in Javascript and Actionscript [Number("1" + the_string) % 1 === 0)], I can't speak for that, but it is exactly what we needed.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 02:39

    This is built on some of the previous answers and comments. The following covers all the edge cases and fairly concise as well:

    const isNumRegEx = /^-?(\d*\.)?\d+$/;
    
    function isNumeric(n, allowScientificNotation = false) {
        return allowScientificNotation ? 
                    !Number.isNaN(parseFloat(n)) && Number.isFinite(n) :
                    isNumRegEx.test(n);
    }
    
    0 讨论(0)
  • 2020-11-22 02:40

    And you could go the RegExp-way:

    var num = "987238";
    
    if(num.match(/^-?\d+$/)){
      //valid integer (positive or negative)
    }else if(num.match(/^\d+\.\d+$/)){
      //valid float
    }else{
      //not valid number
    }
    
    0 讨论(0)
提交回复
热议问题