Javascript - Is a valid number?


  • 0
    A

    The easiest way to find if a number is valid or not is to use the build in method in JS (isNaN)

    The code goes like this:

    /**
     * @param {string} s
     * @return {boolean}
     */
    var isNumber = function(s) {
        if (s) {
            s = s.trim();
            return s !== '' && !isNaN(s);
        }
    };
    

    And if you don't want to use isNaN in methods, then:

    /**
     * @param {string} s
     * @return {boolean}
     */
    var isNumber = function(s) {
        s = s.trim();
        if (s) {
            var num = Number(s, 10);
            return (num + 0 == s);
        }
        return false;
    };
    

  • 0
    N

    Both would fail if the "custom testcase" was "Infinity".


  • 0
    N

    I wen't with this personally.

    var isNumber = function(s) {
        return !!s.trim() 
            && !s.includes('Infinity') 
            && !isNaN(Number(s));
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.