Javascript parseInt detect overflow

How to determine if overflow / underflow occurred while parsing an integer from a string using the parseInt method?

The approach I was thinking of is to convert Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER to a string and check if the string to be checked is in this range.

+5
source share
2 answers

According to MDN, Number.MIN_SAFE_INTEGER is the minimum safe integer in JavaScript (- (2 ^ 53 - 1)) and the Number.MAX_SAFE_INTEGER constant is 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/

+2
source

You need Number.isSafeInteger()

In addition, max int limit 2^53 - 1

In addition, you can store data in Float, so you can avoid the problem altogether. If the application needs to know the overflow condition, perhaps post an expression about the problem, there might be a better way to approach it.

0
source

All Articles