/** * @(#)format.js * * Copyright (c) 2000 by Sundar Dorai-Raj
  * * @author Sundar Dorai-Raj
  * * Email: sdoraira@vt.edu
  * * This program is free software; you can redistribute it and/or
  * * modify it under the terms of the GNU General Public License 
  * * as published by the Free Software Foundation; either version 2 
  * * of the License, or (at your option) any later version, 
  * * provided that any use properly credits the author. 
  * * This program is distributed in the hope that it will be useful,
  * * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  * * GNU General Public License for more details at http://www.gnu.org * * */

function format(number,decimals) {
  var i,d;

  // set default values
  if(number=="") number=parseInt("0");
  if(decimals=="") decimals=parseInt("2");

  // round number to specified number of decimals
  number=""+Math.round(number*Math.pow(10,decimals))*Math.pow(10,-decimals);

  // find index of decimal point
  d=number.indexOf(".");

  // if no decimal point, number is an integer
  // pad number with trailing zeros
  if(d==-1) {
    number=number+".";
    for(i=0;i<decimals;i++)
      number=number+"0";
    return number;
  }

  // if decimal point is first index
  // pad number with leading zero
  if(d==0) {
    number="0"+number;
    d++;
  }

  // if first index is negative sign
  // pad number with leading zero
  if(d==1 && number.substring(0,1)=="-") {
    number="-0" + number.substring(1,number.length);
    d++;
  }

  // truncate number to desired length
  number=number.substring(0,d+decimals+1);

  // if number is shorter than desired length
  // pad number with trailing zeros
  while(number.length<=d+decimals)
    number=number+"0";
  return number;
}


