Google analytics code

Showing posts with label zero. Show all posts
Showing posts with label zero. Show all posts

Friday, September 18, 2009

Flash / ActionScript: String padding (leading zero)

I was working on a date/time format in Flash and needed a way to pad values out so they always took up the same amount of space. For example making sure a month always has two digits. Making sure it displays a "05" instead of "5". I couldn't find anything built into AS2 or AS3 to do this so I wrote something that would. It allows you to pass in a value and pad either the left or right side up to a given amount of characters.

/**
* This function will pad the left or right side of any variable passed in
* elem [AS object]
* padChar: String
* finalLength: Number
* dir: String
*
* return String
*/
function padValue(elem, padChar, finalLength, dir)
{
  //make sure the direction is in lowercase
  dir = dir.toLowerCase();

  //store the elem length
  var elemLen = elem.toString().length;

  //check the length for escape clause
  if(elemLen >= finalLength)
  {
    return elem;
  }

  //pad the value
  switch(dir)
  {
    default:
    case 'l':
      return padValue(padChar + elem, padChar, finalLength, dir);
      break;
    case 'r':
      return padValue(elem + padChar, padChar, finalLength, dir);
      break;
  }
}


This function accepts an object that can be converted to a string with the toString method, the character you want to use for padding, the final length of the string and wither you want it padded on the left or right side using the character "l" or "r".

For example if you have a number you want padded with three 0 so the final outcome will look like "0005" you would call the function like this.
var exampleNumber:Number = 5;
padValue(exampleNumber, "0", 4, 'l');


If you want to use this in FLEX you might want to type the parameters on the function and give it a return value.

Friday, August 28, 2009

Actionscript/Flex: Number Formatting (prefix a leading zero)

I was looking for a simple way to prefix a single digit number with a zero. I thought NumberFormatter would be able to do it, but turns out it can't. There is a project hosted on google for a bunch of tools that aren't included in Flex or Actionscript 3.

http://code.google.com/p/as3corelib/

One of these tools allows you to prefix a number with a zero. It's in com.adobe.utils.NumberFormatter. The method is addLeadingZero(). It's kind of confusing having two NumberFormatter classes, but I didn't write it so there you go.

There's a lot of good stuff in the project, so if you're looking for something Flex doesn't do it might be in there.


I also wrote my own string padding function that can be used in Flex, AS2 or 3. Please see this post for more details.