开发者

as3 - detecting an out-of-range value w/ parseInt()

开发者 https://www.devze.com 2023-03-14 23:48 出处:网络
if i pass parseInt() a string representing an integer larger than 2^31, how do i detect that ? it would be swell if parseInt() returned NaN,

if i pass parseInt() a string representing an integer larger than 2^31, how do i detect that ?

it would be swell if parseInt() returned NaN, but it doesn't.

i could test the number which parseInt returns agains开发者_StackOverflow社区t max int & min int.

anything better ?

tia, orion


If you are assuming the maximum value of return value to be 4,294,967,295 (Max value for uint) then you are mistaken.

The function parseInt returns a Number & not a uint. The maximum value for a Number is 1.79e+308 which is quite large & still if your number is above that, the function parseInt will return NaN.

So you can simply check for NaN & it should work.


You could turn it into a Number first, which can be way way bigger than int, check it against int.MAX_VALUE and int.MIN_VALUE, and then finally cast it to int.

var myNumber:Number = Number(myStringOrSomething);
var myInt:int;
if (myNumber <= int.MAX_VALUE && myNumber >= int.MIN_VALUE) {
    // Number is big (or small) enough, cast it as int
    myInt = Math.round(myNumber) as int;
} else {
    // Failed at converting to int
}


i ended up testing the return against NaN, and also for being in the range [int.MIN_VALUE, int.MAX_VALUE].

here's some examples and the results. (false = not a valid int, true = is a valid int)

"abcde"      , false //
"0XYZ"       , true  // i wish this wasn't the case, but it is.
" 123 "      , true  //
"NaN"        , false //
"85899345912", false //   2^33 - 1
 "2147483647", true  //   2^31 - 1
 "2147483648", false //   2^31
"-2147483647", true  // -(2^31 - 1)
"-2147483648", true  // -(2^31
"-2147483649", false // -(2^31 + 1)
0

精彩评论

暂无评论...
验证码 换一张
取 消