Format Price with ActionScript

ActionScript 2.0 biggest weakness is lack of support for regular expressions. This makes relatively simple things like formatting price (the American way) a bit of a chore. Here’s a solution for those not quite ready to make all their users switch to Flash Player 9.

function formatPrice(orgPrice)
{
orgPriceSpilt = orgPrice.toString();
orgPriceSpilt = orgPrice.split(".");
numString = orgPriceSpilt[0]
newString = "";
index = 1;
trip = 0;
while(numString.length >= index) {
if (trip!=3)
{
//haven't reached 3 chars yet newString = numString.charAt(numString.length - index) + newString;  //add char     index++;
trip++;
}
else { //reached 3 chars, add comma newString = "," + newString;
trip=0;
}
}
if (orgPriceSpilt[1].length < 2)
{
decimal = orgPriceSpilt[1] + "0" } else { decimal = orgPriceSpilt[1]
}
return ("$"+newString+"."+decimal);
}
This entry was posted in ActionScript. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. yauidea
    Posted June 5, 2008 at 8:03 pm | Permalink

    your second line may typo

    // format price
    function formatPrice(orgPrice) {
    orgPriceSpilt = orgPrice.toString();
    orgPriceSpilt = orgPriceSpilt.split(”.”);
    numString = orgPriceSpilt[0];
    newString = “”;
    index = 1;
    trip = 0;
    while (numString.length >= index) {
    if (trip != 3) {
    //haven’t reached 3 chars yet
    newString = numString.charAt(numString.length – index) + newString;
    //add char
    index++;
    trip++;
    }
    else {
    //reached 3 chars, add comma
    newString = “,” + newString;
    trip = 0;
    }
    }
    return (newString);
    }

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word