Simple numbers formatting with "fake" spaces at thousands markers

A little trick to show large numeric values with easy "thousand" separation. Note, we don't modify the text, if you copy/paste it stays a single continuous number.

by Marcin Zukowski

HTML

Input: <br/>
<input id="in" type="text" value="12345678.90"/>
<br/>
<br/>
Output HTML
<pre id="outRaw"></pre>
<br/>
Rendered output (note - these spaces are not really there!): <br/>
<pre id="out"></pre>

CSS

.thousandsSeparator {
  display : inline;
  padding-left : 4px;
}

textarea {
  width: 300px;
}

pre {
  background-color: white;
}

JavaScript

// Posted to http://stackoverflow.com/a/36256628/1457258
//
// This function accepts an integer, and produces a piece of HTML that shows it nicely with 
// some empty space at "thousand" markers. 
// Note, these space are not spaces, if you copy paste, they will not be visible.
function valPrettyPrint(orgVal) {
  // Save after-comma text, if present
  var period = orgVal.indexOf(".");
  var frac = period >= 0 ? orgVal.substr(period) : "";
  // Work on input as an integer
  var val = "" + Math.trunc(orgVal);
  var res = "";
  while (val.length > 0) {
    res = val.substr(Math.max(0, val.length - 3), 3) + res;
    val = val.substr(0, val.length - 3);
    if (val.length > 0) {
    	res = "<span class='thousandsSeparator'></span>" + res;
    }
  }
  // Add the saved after-period information
  res += frac;
  return res;
}

function prettyPrint() {
  var val = this.value;
  var valpp = valPrettyPrint(val);
  document.getElementById('outRaw').innerText = valpp;
  document.getElementById('out').innerHTML = valpp;
}

document.getElementById('in').onchange = prettyPrint;
document.getElementById('in').onchange();