JavaScript parseMoney

In order to change the input number format to currency format, e.g. 12500 => 12,500. The javascript code I write as follows: intimcity nl .

function parseMoney(objID) {
  var obj = document.all[objID]; //get the object
  if(obj.value=='') {
    return; //do no job when the value is empty
  }
  //check number format
  var chkstr = replaceAll(obj.value, ',', '');
  if(chkstr!='' && isNaN(chkstr)) {
    alert('Please enter the right number format!');
    obj.focus(); //focus the object let user remodify
    return;
  }
  //check negative format
  var negative = false;
  if(chkstr.indexOf('-')>=0) {
    negative = true;
    chkstr = chkstr.replace('-', '');
    //omit negative character in advance
    //to prevent -0
  }
  var mArray = chkstr.split('.');
  if(mArray[0]=='') { //in case .xx
    mArray[0] = '0';
  }
  obj.value = parseInt(mArray[0], 10);
  //give back the negative char
  var money = (negative) ? ('-' + obj.value) : obj.value;
  var retstr = '';
  for(var i=money.length-1; i>=0; i--) {
    retstr += money.charAt(money.length-1-i);
    //add comma if it is thousands digit
    //remember to leave out negative char
    if(i%3==0 && i>0 && retstr!='-') {
      retstr += ',';
    }
  }
  if(mArray.length>1) {
     //decimal point exist
    retstr += '.';
    var decimal = '';
    var flag = false;
    for(var i=mArray[1].length-1; i>=0; i--) {
      if(!flag && mArray[1].charAt(i)=='0') {
        continue;
      }
      else if(!flag) {
        flag = true;
      }
      decimal = mArray[1].charAt(i) + decimal;
    }
    if(decimal=='') { //in case x.000
      decimal = '0';
    }
    retstr += decimal;
  }
  if(parseFloat(retstr)=='0') {
    retstr = '0'; //in case 0.0 或 -0.0
  }
  obj.value = retstr;
}
function replaceAll(str, from, to) {
  var idx = str.indexOf(from);
  while(idx>-1) {
    str = str.replace(from, to);
    idx = str.indexOf(from);
  }
  return str;
}

See the test page

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>