3

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

9
  • 3
    C# is irrelevant tag for this question, hence removed Commented Mar 13, 2019 at 7:24
  • 3
    if (BigInt(result) > Number.MAX_SAFE_INTEGER) will tell you if it's greater than the largest Number JS can represent/store Commented Mar 13, 2019 at 7:25
  • also: Java is not Javascript. What have you tried so far? Commented Mar 13, 2019 at 7:25
  • @Jack BigInt is an unneccessary typeconversion there. Commented Mar 13, 2019 at 7:27
  • Which arithmetic overflow? Integer overflow? Number overflow? Invalid operations? Commented Mar 13, 2019 at 7:27

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

@AZ_ indeed, should've checked that instead of trusting on my memory :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.