I would like to know in AS3.0, how do i
pad 0 in front of the integer upon converting to string
eg:
1 --> 0001
11 --> 0011
so that i ll have consistent number of digits…
I would like to know in AS3.0, how do i
pad 0 in front of the integer upon converting to string
eg:
1 --> 0001
11 --> 0011
so that i ll have consistent number of digits…
function fullLength(val:String, targLength:int = 4):String
{
var retS:String = val;
if (val.length < targLength)
{
for (var z:int = 0; z < targLength - val.length; z++)
{
retS = "0" + retS;
}
}
return retS;
}
trace(fullLength("1")); //returns 0001
trace(fullLength("621")); //returns 0621
That should do the trick. :thumb:
edit: I added it as a parameter that defaults to 4. If you want a different length, change the default, or pass it like this:
trace(fullLength(myString, targetLength));
i thought there should be a built in function for this …
but thanks anyway.
You could also do:
function fullLength(val:String, targLength:int = 4):String {
return val.length < targLength ? new Array(targLength - val.length + 1).join("0") + val : val;
}
trace(fullLength("1")); //returns 0001
trace(fullLength("621")); //returns 0621
Or just have it untyped until you pad the 0 and then cast it.
:: Copyright KIRUPA 2024 //--