js格式化数字

时间:2023-02-26 20:10:08
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>格式化数字</title>
</head>
<body>
<script type="text/javascript">
/**
方法一 不加千分位(整数部分最大15位,小数为最多4位)
object --文本框对象
n --保留的小数位
*/
function fmoney(object,n){
    // ^-?[0-9]+\.?[0-9]*$ 验证浮点数
    var num =  object.value;
    var start = num.indexOf('-');
    if(start == 0){
        num = num.substring(1,15);
    }else{
        num = num.substring(0,15);
    }
    num = parseFloat((num + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";   
    if (isNaN(num) || ((num + "").replace(/\s/g, "")) == "") {
        object.value = "";
        return;
    }
    n = n > 0 && n <= 20 ? n : 2;   
    var l = num.split(".")[0].split("").reverse(),r = num.split(".")[1],t = "";   
    for(var i = 0; i < l.length; i ++ ){   
      //t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : ""); //加千分位  
      t += l[i];   
    }   
    if(start == 0){
        object.value = "-"+t.split("").reverse().join("") + "." + r;
    }else{
        object.value = t.split("").reverse().join("") + "." + r;
    }
}   
/**
方法二 加千分位 (整数部分最大15位)
object --文本框对象
n --保留的小数位
*/
function simpleFormat(object,n){
    var num = object.value;
    num = num.substring(0,15);
    num = parseFloat((num + "").replace(/[^\d\.-]/g, "")).toFixed(n)+"";   
    if (isNaN(num) || ((num + "").replace(/\s/g, "")) == "") {
        object.value = "";
        return;
    }
    object.value = num;
    var value = num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")  
    object.value = value;
}
function rmoney(s){   
   return parseFloat(s.replace(/[^\d\.-]/g, ""));   
}
</script>
<input type="text" id="11" style="width:200px" onblur='fmoney(this,4)'/><input type="button" value="还原" onclick="r11()"><br>
<input type="text" id="33" style="width:200px" onblur='simpleFormat(this,4)'/><input type="button" value="还原" onclick="r33()">
<script type="text/javascript">
function r11(){
    var value = document.getElementById("11").value;
    alert(rmoney(value));
}
function r33(){
    var value = document.getElementById("33").value;
    alert(rmoney(value));
}
</script>
</body>
</html>