How to detect if an overflow/underflow is occurred when parsing integer from string using parseInt method?
The approach I thought of is to convert the Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER to string and check if the string to be checked lies in this range.
According to MDN Number.MIN_SAFE_INTEGER constant represents the minimum safe integer in JavaScript (-(2^53 - 1)) and Number.MAX_SAFE_INTEGER constant represents the maximum safe integer in JavaScript (2^53 - 1). So It will work
var str = '00000010323245498540985049580495849058043';
var num = parseInt(str,10);
if( num > Number.MAX_SAFE_INTEGER) {
alert("Overflow!");
}
Here is the fiddle
https://jsfiddle.net/Refatrafi/91rcnoru/2/
You need Number.isSafeInteger()
Also, max int limit is 2^53 - 1
Also, you can store data in a Float, this way you can avoid the problem altogether. If you application needs to know overflow condition, maybe post the problem statement, there could be a better way to approach it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With