Formatting numbers in Flash

Posted on June 1, 2009

1


This evening I created the following script to format numbers in Flash.

I use the “# ### 00” structure to define the delimiters for thousands and to define the decimals separator.

Code:

function formatNumber(value:String,formatter:String)
{
 /*
 VERSION: BETA 0.1, Juni 01, 2009

 This is a simple method to format numbers
 Rounding is not included to make it a bit faster for a lot of numbers to round (in a list)

 Formatter #,00 will not work. There has to be a thousands-seperator in there
 123.34 with formatter #.###,00 becomes 123,34
 123.346 with formatter #.###,00 becomes 123,34

 1234.34 with formatter #.###,00 becomes 1.234,34
 1234.34 with formatter # ###,00 becomes 1 234,34

 and so on
 */
    var VAL:Array; // Will contain major and minor part of number
    var FRMT:Array; // Will contain formatter items

    // CLEAR FORMATTER FROM STUFF PEOPLE DO, BUT US MACHINES DO NOT NEED
    formatter=formatter.split("#").join("");

    // SEPARATE DECIMALS
    if(value.indexOf(",")>=0)
    {
       VAL=value.split(","); // European format: comma is decimal separator
    }
    else
    {
       VAL=value.split(".");    
    }
    if(!VAL[1])
    {
       VAL[1]="00";    // Make sure we have some decimals
    }

    var minorCount=formatter.length-2; // Get the number of decimals
    FRMT=formatter.split(""); // Split the formatter

    // PUT THE STUFF IN STRINGS
    var major:String=VAL[0];
    var minor:String=VAL[1]+"000000000"; // Add some zeroes in case we have high detail
    var cntTo3:int=0; // Count to three to place thousands seperator

    var ml:int=major.length-1; // Get the length of the integer value
    var result:String=""; // Define the result variable
    var nums:Array=major.split(""); // Split major number to array

    // MAJOR: START BUILDING FROM END TO FORMAT THE MAJOR NUMBER
    for (var i=ml;i>=0;i--)
    {
       cntTo3++;
       if(cntTo3==4)
       {    
          result=FRMT[0]+result // PLACE THOUSAND SEPERATOR
          cntTo3=0;
       }    
       result=nums[i]+result;    
    }
    // FORMAT THE DECIMALS
    if(minorCount>0)
    {
       result+=FRMT[1]+" "+minor.substr(0,minorCount)
    }
    // RETURN THE RESULT
    return result;
 }
Advertisements
Posted in: Formatting stuff