Validate number

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

More like this

  • Number is negative zero

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

    JavaScript, Math · Oct 20, 2020

  • Luhn check

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

    JavaScript, Math · Jan 30, 2022

  • Percentile of matches

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

    JavaScript, Math · Oct 22, 2020