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
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.
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.