How to check if integer multiplication will overflow in JavaScript

1 Answer

0 votes
function multiplyWillOverflow(x, y) {
    if (x === 0) return false;

    if (y > Number.MAX_SAFE_INTEGER / x) return true;
    if (y < Number.MIN_SAFE_INTEGER / x) return true;

    return false;
}

let x = 3, y = 14727836;
console.log(multiplyWillOverflow(x, y) ? "true" : "false");

x = 133883;
y = 97967967891872783642;
console.log(multiplyWillOverflow(x, y) ? "true" : "false");

 
 
/*
run:
 
false
true
 
*/

 



answered May 18, 2025 by avibootz
...