简体   繁体   中英

Detect Number overflow in Javascript

Is there any builtin function in javascript which will notify, overflow of arithmetic operation on number data type? Like c# and Java have.

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.

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!" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM