javascript金額每隔三位加逗號格式化程式碼例項

admin發表於2017-04-02

在實際應用中,如果遇到表示金錢的數字,最好對其進行格式化,以便於閱讀識別。

下面就是一段能夠實現此功能的程式碼例項,需要的朋友可以做一下參考。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript">
function run(obj){
  var objvalue = obj.value.replace(/[,]/g, ""),
      objlength = objvalue.length,
      dtmp = objvalue.indexOf("."),
      neg = objvalue.indexOf("-");
  var inttmp = 0,
      floattmp = -1;
  if(dtmp != -1){
    inttmp = dtmp == 0 ? "0" : new String(objvalue).substring(0, dtmp);
    floattmp = new String(objvalue).substring(dtmp + 1, objlength + 1);
    floattmp = floattmp.replace(/[^0-9]/g, "");
  }
  else{
    inttmp = objvalue;
  }
  if (neg == 0) {
    inttmp = inttmp.replace(/[-]/g, "");
  }
  inttmp = inttmp.replace(/[^0-9]/g, "");
  var tmp = "", str = "0000";
  for (; inttmp.length > 3; ) {
    var temp = new String(inttmp / 1000);
    if (temp.indexOf(".") == -1) {
      tmp = ",000" + tmp;
      inttmp = temp;
    }
    else {
      var le = new String(temp).split(".")[1].length;
      tmp = "," + new String(temp).split(".")[1] + str.substring(0, 3 - le) + tmp;
      inttmp = new String(temp).split(".")[0];
    }
  }
  inttmp = inttmp + tmp;
  obj.value = neg == 0 ? "-" + inttmp + runing(floattmp) : inttmp + runing(floattmp);
}
 
function runing(val) {
  if(val != "-1" && val != "") {
    var valvalue = 0 + "." + val;
    if (val.length >= 2) {
      valvalue = parseFloat(valvalue).toFixed(2);
    }
    var temp = "." + valvalue.split(".")[1];
    return temp;
  }
  else if (val != "0" && val == "") {
    return ".";
  }
  else {
    return "";
  }
}
window.onload=function(){
  var otxt=document.getElementById("txt");
  run(otxt)
}
</script>
</head>
<body>
<input id="txt" type="text" value="254674"/>
</bod>
</HTML>

相關文章