Skip to content

Displaying number with thousand seperator

An answer to this question on Stack Overflow.

Question

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][1]

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>

[1]: http://jsfiddle.net/giangvy1011/uhLnhzxk/

Answer

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.