Validate number

OSCC · JavaScript, Math · Oct 22, 2020

Checks if the given value is a number.

  • Use parseFloat() to try to convert n to a number.
  • Use Number.isNaN() and logical not (!) operator to check if num is a number.
  • Use Number.isFinite() to check if num is finite.
  • Use Number and the loose equality operator (==) to check if the coercion holds.
const validateNumber = n => {
  const num = parseFloat(n);
  return !Number.isNaN(num) && Number.isFinite(num) && Number(n) == n;
}
validateNumber('10'); // true
validateNumber('a'); // false

Recommended snippets

  • Number is negative zero

    JavaScript, Math

    Checks if the given value is equal to negative zero (-0).

  • Luhn check

    JavaScript, Math

    Implements the Luhn Algorithm, used to validate a variety of identification numbers.

  • Percentile of matches

    JavaScript, Math

    Calculates the percentage of numbers in the given array that are less or equal to the given value.