Try executing the following in JavaScript:
parseInt(\'01\'); //equals 1
parseInt(\'02\'); //equals 2
parseInt(\'03\'); //equals 3
parseInt(\'04\'); //equals
If you know your value will be in the signed 32 bit integer range, then ~~x
will do the correct thing in all scenarios.
~~"08" === 8
~~"foobar" === 0
~~(1.99) === 1
~~(-1.99) === -1
If you look up binary not (~
), the spec requires a "ToInt32" conversion for the argument which does the obvious conversion to an Int32 and is specified to coerce NaN
values to zero.
Yes, this is incredibly hackish but is so convenient...