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)
{
newString = numString.charAt(numString.length - index) + newString; index++;
trip++;
}
else { newString = "," + newString;
trip=0;
}
}
if (orgPriceSpilt[1].length < 2)
{
decimal = orgPriceSpilt[1] + "0" } else { decimal = orgPriceSpilt[1]
}
return ("$"+newString+"."+decimal);
}
This entry was written by
Alastair, posted on
August 6, 2006 at 5:07 pm, filed under
ActionScript. Bookmark the
permalink. Follow any comments here with the
RSS feed for this post.
or leave a trackback:
Trackback URL.
© Copyright 2006 - 2010 Alastair Dawson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
One Comment
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);
}