Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Number overflow in Javascript

Tags:

javascript

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

like image 662
Abhay Kumar Avatar asked Sep 09 '26 01:09

Abhay Kumar


1 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!"
like image 61
Ömür Alçin Avatar answered Sep 10 '26 13:09

Ömür Alçin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!