9.5 ToInt32

2010-05-04

int ToInt32(input:mixed)

Convert the input to an unsigned integer (number) in the range -231 through 231+1, inclusive. The special cases NaN, +0, -0 and any infinity will result in +0.

Note that you have no direct access to this function from within Ecmascript.

Code: (Meta Ecma)
function ToInt32(input){
if (isNaN(input) || input === +0 || input === -0 || input === infinity || input === -infinity) return +0;
// since the edge cases are gone, this simply does exactly the same as the specification
var posInt = ToNumber(input);
var int32bit = posInt%(Math.pow(2,32));
if (int32bit >= Math.pow(2,31)) return int32bit - Math.pow(2,32);
return int32bit;
}

So this actually behaves like ToNumber, except that it also makes sure the return value is within the (signed) 32bit range.

The function is idempotent; When you apply it to a number it returned, that value does not change anymore.

ToInt32(ToUint32(x)) is equal to ToInt32(x) for all values of x. This is why infinity is mapped to +0.