AS3: How to Convert Number to String

Contributor Icon Contributed by davak Date Icon May 6, 2007  
Tag Icon Tagged: Computer programming

Frequently, it is nice to convert numbers to strings in actionscript 3. For example, this will correct the error — 1067: Implicit coercion of a value of type Number to an unrelated type String.


In my neverending journey to teach myself actionscript, I have once again started pounding through some code.

In short to convert a number to a string, use the following construct:

text = String(number);

If you try to avoid this step, it’ll throw the following error…

1067: Implicit coercion of a value of type Number to an unrelated type String.

Here is some example code that will throw the error:


var time:Date= new Date();
var txt:String;
txt = time.milliseconds;

This code works correctly:


var time:Date= new Date();
var txt:String;
txt = String(time.milliseconds);

Previous recipe | Next recipe |
 
  • littleman80
    how about if I have a number, i.e.: 23 and I want to converted it to the string "0023" (with 4 digits i.e.)?...
  • same problem
    I'm getting a number from an XML, looks like 123,456,78
    i then myString.split(",").join("");
    gives me "12345678"
    now I want to use it in some math,
    i tried Number(myString);
    that just gives me the error above
  • jk
    How to do whith that?:

    var D:String;
    D = String(b * b - 4 * a * c);
  • Daniel
    thats cool man, but how would you know wich class to add so you can use the "string()" converter
  • jenny
    or you could use (time.milliseconds).toString()
  • Christo
    That doesn't work.
  • @ littleman80
    var num:Number = 23;
    var StringConverted:String = "00"+String(num);
    trace(StringConverted);

    @justin
    to convert a string to number use this
    var TheString:String = "12345678";
    var TheNumber:Number = parseInt(TheString);
    trace(TheNumber * 2) // by using * u can test that its really a number
blog comments powered by Disqus