Wednesday, August 6, 2008

Formatting currency

Following on from the previous entry about formatting numbers, it's a simple task to convert the same function into one that accepts currency symbols:

function formatCurrency(num:Number, comma:Boolean, currency:String):String {
 // return a zero value if num is not valid
 if (isNaN(num)) {
  return "0.00";
 }
 // return a blank value if currency is not valid
 if (currency == undefined) {
  currency = "";
 }
 // round num to the nearest 100th   
 num = Math.round(num * 100) / 100;
 // convert num to a string
 var num_str:String = String(num);
 // seperate any decimals from the whole numbers
 var num_array = num_str.split(".");
 // if there are no decimals add them using "00"
 if (num_array[1] == undefined) {
  num_array[1] = "00";
 }
 // if the decimals are too short, add an extra "0"   
 if (num_array[1].length == 1) {
  num_array[1] += "0";
 }
 // separate whole numbers with commas  
 // if required (comma = true)
 if (comma) {
  var whole_array:Array = new Array();
  var start:Number;
  var end:Number = num_array[0].length;
  while (end > 0) {
   start = Math.max(end - 3, 0);
   whole_array.unshift(num_array[0].slice(start, end));
   end = start;
  }
  num_array[0] = whole_array.join(",");
 }
 // construct a return string joining  
 // the whole numbers with the decimals
 // and prefixing a currency symbol
 return (currency + num_array.join("."));
}
trace(formatCurrency(1234.5, true, "£"));
// outputs £1,234.50
trace(formatCurrency(1234.5, true, "\u00a5"));
// outputs ¥1,234.50

No comments: