-
[RESOLVED] How to add zeros to beginning of a number?
Sorry, the title maybe misleading but;
All I wanted to know is, how to make string represents of numbers that have specific amount of digits.
For examle:
1 = 0001
34 = 0034
1024 = 1204
Is there any function or easy way to achieve this?
Last edited by xxakkusxx; 02-27-2012 at 03:55 PM.
Reason: Bad english use + Title change
-
I made my own function.
Actionscript Code:
function addZero(entryNumber:Number, desiredLength:Number):String { var s:String = String(entryNumber); var l:Number = s.length; l = desiredLength-l; var zeros:String = new String; for(l=l;l>0;l-=1) { zeros+="0"; } return zeros+s; }
Last edited by xxakkusxx; 02-27-2012 at 04:09 PM.
Reason: Bad coding
-
Have you considered what you would need to do to this existing code if the desired length was 100 and the entry length was 10? Very ugly code.
Also you know you can convert a number to a string then get the length property to figure out the entry length, no need for that while loop.
Finally, since you know the difference between the desired length and the entry length, you can use a for loop to add the zero character to an empty string, then return the empty string plus the entry number.
-
Actually, I just needed it for writing dates such as 01.02.0003, my desired length is only 4. And I wrote this codes on my first attempt, I didn't tried to improve it.
-
I see. Well it never hurts to think of ways to improve code. Gets the brain juices flowing. Anyways if your issue is resolved it'll be good to set this thread to resolved with the Thread Tools above the first post.
-
I changed the code and title, thanks for your advices
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|