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

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 against max int & min int.

anything better ?

tia, orion

Answers


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
}

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.


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)

Need Your Help

Attaching an Object Residing on Domino Server to Email (Lotusscript preferred)

email lotus-domino attachment

Not sure if this question is more appropriate for ServerFault or StackOverflow, sorry if it should belong elsewhere!

Admin login - $_SESSION is not defined properly

php mysql login admin

How do I define my $_SESSION['amyusername']; and $_SESSION['amypassword']; properly?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.