Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 951
greg Avatar asked May 27 '11 01:05

greg


3 Answers

In AS3, you can try:

parseInt('04755', 10)

10 above is the radix.

like image 88
Rahul Singhai Avatar answered Nov 13 '22 09:11

Rahul Singhai


parseInt(yourString);

...is the correct answer. .parseInt() is a top-level function.

like image 33
Engineer Avatar answered Nov 13 '22 10:11

Engineer


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.

like image 8
Marty Avatar answered Nov 13 '22 11:11

Marty