-2

I have a input field for user to input number. This number will be displayed in span tag as user is typing. And i would like to format this number in span tag with thousand separator.

Currently, it only show exactly what is typing without thousand separator: JSFiddle

Here is my simplified code:

<!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>
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Giang Nguyen
  • 495
  • 8
  • 22
  • possible duplicate of [How to print a number with commas as thousands separators in JavaScript](http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – ASGM Jan 22 '15 at 18:05
  • @ASGM, the question you link to refers to integers whereas this question seems to refer to numbers generally. – Richard Jan 22 '15 at 18:28

2 Answers2

3

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;
    });
}
<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>
juvian
  • 15,875
  • 2
  • 37
  • 38
0

An answer without loops.

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] : "");
}
<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>

See also accounting.js which handles this sort of thing quite nicely.

Richard
  • 56,349
  • 34
  • 180
  • 251