Most people who read this are not Flash developers, but I know some of you are, so I thought I’d post this little script I made.
I searched all over the web for a simple function that would format numbers nicely in Flash. I couldn’t find one I liked, so I put this one together. Feel free to copy and paste it as you will, if you think you might find it useful.
It takes 4 parameters – the number you’d like to format, the number of digits you’d like for the decimal, the strign you’d like to use as a seperator for thousands, and the string to use for the decimal character.
function numberFormat(myNum:Number, precision:Number, seperator:String, decimal:String) { // get a string myString = String(myNum); // if there is a decimal… if (myString.indexOf(".", 0) != -1) { decimalIndex = myString.indexOf(".", 0); decimalNum = myString.substring(decimalIndex, myString.length); // otherwise } else { decimalIndex = myString.length; decimalNum = "."; } // split the number at the decimal number = myString.substring(0, decimalIndex); // make a new var that we will create with the commas newNumber = ""; // add the commas… for (i=number.length-1; i>=0; i--) { newNumber = newNumber+number.charAt(number.length-1-i); if ((i%3 == 0) and (i != 0)) { newNumber = newNumber+seperator; } } // now make the decimal side - first, trim off the "." decimalNum = decimalNum.substring(1, decimalNum.length); // if it's the appropriate number of digits already, we are done! // otherwise… if (!(decimalNum.length == precision)) { // if we just need to add zeros, if ((decimalNum == 0) or (decimalNum.length0) { return newNumber+decimal+decimalNum; } else { return newNumber; } } trace(numberFormat(123456789, 0, ",", ".")); // returns "123,456,789" trace(numberFormat(12345.6789, 1, " ", ",")); // returns "12 345,7" trace(numberFormat(12345678.9, 2, ",", ".")); // returns "12,345,678.90"