用千位分隔符显示数字

时间:2015-01-22 17:59:28

标签: javascript

我有一个输入字段供用户输入数字。当用户输入时,此数字将显示在span标记中。我想在span标签中用千位分隔符格式化这个数字。

目前,它只显示没有千位分隔符的输入内容: JSFiddle

这是我的简化代码:

<!DOCTYPE html>
<html>
<head>
<script>
function charPreview(){
var x = document.getElementById("frm_price").value;
document.getElementById("frm_price_preview").innerHTML = x;
}
</script>
</head>
<body>
<form>
Price: <input type='text' id='frm_price'
onkeyup="charPreview()"> 
<span id="frm_price_preview"></span>
</form>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

&#13;
&#13;
function charPreview(){
  var x = document.getElementById("frm_price").value;
  document.getElementById("frm_price_preview").innerHTML = decimalWithCommas(x);
}


function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function decimalWithCommas(n){
    var rx=  /(\d+)(\d{3})/;
    return String(n).replace(/^\d+/, function(w){
        while(rx.test(w)){
            w= w.replace(rx, '$1,$2');
        }
        return w;
    });
}
&#13;
<form>
Price: <input type='text' id='frm_price' onkeyup="charPreview()">&nbsp&nbsp&nbsp <span id="frm_price_preview">This is where to show number as user is typing</span>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

没有循环的答案。

&#13;
&#13;
function charPreview(){
  var x = document.getElementById("frm_price").value;
  document.getElementById("frm_price_preview").innerHTML = numberWithCommas(x);
}


function numberWithCommas(n) {
  var parts=n.toString().split(".");
  return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
&#13;
<form>
Price: <input type='text' id='frm_price' onkeyup="charPreview()">&nbsp&nbsp&nbsp <span id="frm_price_preview">This is where to show number as user is typing</span>
</form>
&#13;
&#13;
&#13;

另见accounting.js可以很好地处理这类事情。