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

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

    2019: Including ES3, ES6 and TypeScript Examples

    Maybe this has been rehashed too many times, however I fought with this one today too and wanted to post my answer, as I didn't see any other answer that does it as simply or thoroughly:

    ES3

    var isNumeric = function(num){
        return (typeof(num) === 'number' || typeof(num) === "string" && num.trim() !== '') && !isNaN(num);  
    }
    

    ES6

    const isNumeric = (num) => (typeof(num) === 'number' || typeof(num) === "string" && num.trim() !== '') && !isNaN(num);
    

    Typescript

    const isNumeric = (num: any) => (typeof(num) === 'number' || typeof(num) === "string" && num.trim() !== '') && !isNaN(num as number);
    

    This seems quite simple and covers all the bases I saw on the many other posts and thought up myself:

    // Positive Cases
    console.log(0, isNumeric(0) === true);
    console.log(1, isNumeric(1) === true);
    console.log(1234567890, isNumeric(1234567890) === true);
    console.log('1234567890', isNumeric('1234567890') === true);
    console.log('0', isNumeric('0') === true);
    console.log('1', isNumeric('1') === true);
    console.log('1.1', isNumeric('1.1') === true);
    console.log('-1', isNumeric('-1') === true);
    console.log('-1.2354', isNumeric('-1.2354') === true);
    console.log('-1234567890', isNumeric('-1234567890') === true);
    console.log(-1, isNumeric(-1) === true);
    console.log(-32.1, isNumeric(-32.1) === true);
    console.log('0x1', isNumeric('0x1') === true);  // Valid number in hex
    // Negative Cases
    console.log(true, isNumeric(true) === false);
    console.log(false, isNumeric(false) === false);
    console.log('1..1', isNumeric('1..1') === false);
    console.log('1,1', isNumeric('1,1') === false);
    console.log('-32.1.12', isNumeric('-32.1.12') === false);
    console.log('[blank]', isNumeric('') === false);
    console.log('[spaces]', isNumeric('   ') === false);
    console.log('null', isNumeric(null) === false);
    console.log('undefined', isNumeric(undefined) === false);
    console.log([], isNumeric([]) === false);
    console.log('NaN', isNumeric(NaN) === false);
    

    You can also try your own isNumeric function and just past in these use cases and scan for "true" for all of them.

    Or, to see the values that each return:

提交回复
热议问题