Hello and welcome to the start of a new line of AS3 articles, focusing on being very short and to the point. so anyway i was walking down the road and i caught the glimps of a penny on the floor, so i went to pick it up and accidently fell into an alternate dimention where i met a rather large yellow creature proclaiming to be the king of AS3. So i just said stage.removeChild(Monster_mc); and he was defeated…
…then i wrote this tutorial.
OK so, why would you want to convert a String to a Number and vice versa? Well it could be for a whole range of reasons though mainly if flash spits out this message:
“1067: Implicit coercion of a value of type String to an unrelated type Number.”
You mostly get this if you’ve tried to run a numerical calculation on a string, which just dosen’t work. However hope is not lost! you can use two of AS3’s handy functions to convert them on the fly!
Say i have these two variables, one a String, the other a Number.
var myString:String = "123"; var myNumber:Number = 42;
Now say you want to add them together.
var myCalc:Number = myNumber + myString; trace(myCalc);
If you ran that calculation you’d get the error mentioned above. However if you convert the ‘myString’ varible to a Number the calculation will run perfectly.
var myCalc:Number = myNumber + Number(myString); trace(myCalc);
this will now output 165 in the output window.
if you do the same but convert the Number to a string like so…
(remember to change the var ‘myCalc’ to a String)
var myCalc:String = String(myNumber) + myString; trace(myCalc);
Flash will output 42123 as it would if you were adding to a string.
Well thats it, if you think i’ve missed something please leave a comment ![]()
You're Thoughts & Discussion
No comments for “AS3 Quick Tips: String to Number Conversion (and vice versa)”
Post you're thoughts...