Search code examples
stringactionscriptint

Actionscript Convert String to Int


I am using Actionscript 2.0

In a Brand new Scene. My only bit of code is:

    trace(int('04755'));
    trace(int('04812'));

Results in:

  • 2541

  • 4812

Any idea what I am doing wrong/silly?

By the way, I am getting this source number from XML, where it already has the leading 0. Also, this works perfect in Actionscript 3.


Solution

  • Converting a string with a leading 0 to a Number in ActionScript 2 assumes that the number you want is octal. Give this function I've made for you a try:

    var val:String = '00010';
    
    function parse(str:String):Number
    {
        for(var i = 0; i < str.length; i++)
        {
            var c:String = str.charAt(i);
            if(c != "0") break;
        }
    
        return Number(str.substr(i));
    }
    
    trace(parse(val)); // 10
    trace(parse(val) + 10); // 20
    

    Basically what you want to do now is just wrap your string in the above parse() function, instead of int() or Number() as you would typically.