//-----------------------------------------------------------------------------
// file: format.js
// by  : Nick
// desc: formats a number
//-----------------------------------------------------------------------------

//==========================================================
// func: formatNumber(price)
// desc: formats a number to british currency
// args: price - the number to be formatted
// retn: the formatted number
//==========================================================
function formatNumber(price)
{
  // check for zero cost
  if (!price)
    output = "0.00";
  else
  {  
    // convert to string
    price = price + "";
    
    // find the separator
    decimal = price.indexOf(".");
    
    // if no decimal point is specified
    if (decimal != -1)
      pounds = price.substr(0, price.indexOf("."));
    else
      pounds = price + "";
     
    // work out the number to offset the pounds separators by
    offset = pounds.length % 3;
    
    // make sure some offset is taken
    if (offset == 0)
      offset = 3;
    
    // number of separators needed
    number = Math.floor((pounds.length - 1) / 3)

    // add the separators in for the pounds
    for (i = 0; i < number; i ++)
    {
      position = offset + (i * 3) + i;
      pounds   = pounds.substring(0, position) + "," + pounds.substring(position, pounds.length);
    }
        
    // if no pence are specified
    if (decimal != -1)
    {
      // get the pence
      pence = price.substring(decimal + 1, price.length);
      
      // work out the pence if needs rounding
      if (pence.length > 2)
        pence = Math.round(pence / (Math.pow(10, pence.length - 2)));
        
      // turn pence into a string
      pence = pence + "";
    }
    else
      pence = "";
    
    // catch any pence less than 10
    while (pence.length < 2)
      pence = "0" + pence;
    
    output = pounds + "." + pence;
  }
  
  return output;
}