Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript parseInt detect overflow

Tags:

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.

like image 306
Prashant Bhanarkar Avatar asked Aug 30 '16 13:08

Prashant Bhanarkar


2 Answers

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/

like image 113
Rafi Ud Daula Refat Avatar answered Oct 11 '22 03:10

Rafi Ud Daula Refat


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.

like image 24
Prateek Gupta Avatar answered Oct 11 '22 01:10

Prateek Gupta