65. Valid Number


Problem

Validate if a given string is numeric.

Some examples:

"0" => true

" 0.1 " => true

"abc" => false

"1 a" => false

"2e10" => true

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.

Solution

Solution1

Let engine do the heavy work.

Number() or +string trims both whitespaces, doesn't accept illegal characters but parses empty string as 0. ``

parseFloat trims leading whitespace, parses empty string as NaN but accepts tailing illegal characters.

/**
 * @param {string} s
 * @return {boolean}
 */
var isNumber = function(s) {
    return !isNaN(parseFloat(s)) && !isNaN(Number(s))
    // return !isNaN(parseFloat(s)) && !isNaN(+s)
    // return !/^\s*$/.test(s) && !isNaN(Number(s))
};

Solution2

RegExp.

I'm not an RegExp expert so my answer is pretty straight forward.

  • ^\s* and \s*$ match the leading and tailing whitespace
  • [+|-]?
  • (float number)(e[+|-]?\d+)? matches the scientific notation
  • inside float number, (\d+)|(\d+\.\d*)|(\d*\.\d+)
    • \d+ matches Integer
    • (\d+\.\d*)|(\d*\.\d+)ensures at least one side of the decimal mark is number
/**
 * @param {string} s
 * @return {boolean}
 */
var isNumber = function(s) {
    return /^\s*[+|-]?((\d+)|(\d+\.\d*)|(\d*\.\d+))(e[+|-]?\d+)?\s*$/.test(s)
};

results matching ""

    No results matching ""