Currency format
Numeric value currency formatting with selectable decimal precision formatting and rounding where applicable
by Mark Hendricks
HTML
<select name="decimal_select" id="decimalselect" onChange="display();")>
<option value="">Select Decimal Precision</option>
<option value="0">0</option>
<option value="1">0.1</option>
<option value="2">0.12</option>
<option value="3">0.123</option>
<option value="4">0.1234</option>
<option value="5">0.12345</option>
<option value="6">0.123456</option>
<option value="7">0.1234567</option>
<option value="8">0.12345678</option>
<option value="9">0.123456789</option>
</select>
<div id="container">
<div id="unformatted"></div>
<div id="formatted"></div>
</div>
CSS
#unformatted, #formatted {
float: left;
margin-right: 20px;
}
JavaScript
Number.prototype.format = function(n, x) {
var re = '(\\d)(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$1,');
};
var numbers = [1, 12, .123, 1234, 12.345, 123456, 1.234567, 12345.67, 123456.789, 0, .123456789];
var unformatted = document.getElementById('unformatted');
unformatted.innerHTML = "<p>Unformatted:</p>";
for (var i = 0, len = numbers.length; i < len; i++) {
unformatted.innerHTML += numbers[i] + "<br />";
}
function display() {
var formatted = document.getElementById('formatted');
var selectedDecimal = document.getElementById("decimalselect").value;
formatted.innerHTML = "<p>Formatted:</p>";
for (var i = 0, len = numbers.length; i < len; i++) {
formatted.innerHTML += "$" + numbers[i].format(selectedDecimal) + "<br />";
}
//reset selectbox without triggering onSelect
document.getElementById("decimalselect").selectedIndex = 0; // -1 is blank
}