💾n.isEqual()

test if two numbers are "essentially" equal.

JSvalueprimitivenumberNumber+ext ⟩ num.isEqual()

test if two numbers are "essentially" equal.

// ⭐️ areEqualNumbers(x, y {threshold})
function areEqualNumbers(x, y, {threshold = Number.EPSILON}={}) { 
    return Math.abs(x - y) < threshold; 
}

// ⭐️ a.isEqual(b, {threshold})
Number.prototype.isEqualTo = function(n, {threshold = Number.EPSILON}={}){
    return areEqualNumbers(this, n, {threshold});
};

💈範例:

const eps = Number.EPSILON;         // 2^(-52) (very small)
const a = Math.pow(10, 300);        // 10^300  (very big)

[
    Number.EPSILON,                 //  2.220446049250313e-16 (2^(-52))
    
    (0.1 + 0.2) - 0.3,              //  5.551115123125783e-17
    0.3 - (0.1 + 0.2),              // -5.551115123125783e-17
    0.1 + 0.2 === 0.3,              // ❗️ false (should be true)

    1.5 + eps > 1.5,                // true
    2.5 + eps === 2.5,              // ❗️ true  (should be false)

    areEqualNumbers(0.1+0.2, 0.3),  // true
    (0.1 + 0.2).isEqualTo(0.3),     // true

    // big numbers
    (a + 1).isEqualTo(a),           // ❗️ true  (should be false)
    (a + 1) - a,                    // ❗️ 0️     (should be 1)   

    // test threshold
    (0.1).isEqualTo(0.11, {threshold: 0.05}),    // true

].forEach(x => log(x));

Last updated