Approximately number equality

OSCC · JavaScript, Math · Nov 1, 2020

Checks if two numbers are approximately equal to each other.

  • Use Math.abs() to compare the absolute difference of the two values to epsilon.
  • Omit the third argument, epsilon, to use a default value of 0.001.
const approximatelyEqual = (v1, v2, epsilon = 0.001) =>
  Math.abs(v1 - v2) < epsilon;
approximatelyEqual(Math.PI / 2.0, 1.5708); // true

Would you like to help us improve 30 seconds of code?Take a quick survey

Recommended snippets

  • Number is negative zero

    JavaScript, Math

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

  • Number is power of two

    JavaScript, Math

    Checks if the given number is a power of 2.

  • Luhn check

    JavaScript, Math

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