Is there any builtin function in javascript which will notify, overflow of arithmetic operation on number data type? Like c# and Java have.
2 Answers
Check from this site : isSafeInteger
var x = Number.MAX_SAFE_INTEGER + 1;
var y = Number.MAX_SAFE_INTEGER + 2;
console.log(Number.MAX_SAFE_INTEGER);
// expected output: 9007199254740991
console.log(x);
// expected output: 9007199254740992
console.log(y);
// expected output: 9007199254740992
console.log(x === y);
// expected output: true
function warn(a) {
if (Number.isSafeInteger(a)) {
return 'Precision safe.';
}
return 'Precision may be lost!';
}
console.log(warn(Number.MAX_SAFE_INTEGER));
// expected output: "Precision safe."
console.log(warn(x));
// expected output: "Precision may be lost!"
console.log(warn(y));
// expected output: "Precision may be lost!"
Comments
Unlike the languages you were referencing, JavaScript does not throw if an invalid math operation is done. Instead, it returns special number values to notify you (doing Math on them always results in that specific value again, so you can just check for them at the end of an arithmetic chain):
NaN // Operation could not be done
Infinity // Number was too large
-Infinity // Number was too small
For all those three special cases you can use isFinite to check against:
// a = 1000, b = 1000, c = 1 -> Infinity
// a = -1000, b = 1001, c = 1 -> -Infinity
const a = 2, b = 51, c = 0; // divide by zero -> NaN
const result = a ** b / c;
if(!isFinite(result)) {
console.log("invalid operation");
}
Also be aware that JavaScript numbers are floating point, with a precise integer range between (-2 ** 53, 2 ** 53), every integer outside of that will lose accuracy. The same applies to any non integer arithmetic which is never accurate.
if (BigInt(result) > Number.MAX_SAFE_INTEGER)will tell you if it's greater than the largestNumberJS can represent/storeBigIntis an unneccessary typeconversion there.