I use the following function to format numbers:
function formatNumber(value, precision) {
if (Number.isFinite(value)) {
// Source: kalisjoshua's comment to VisioN's answer in the following stackoverflow question:
// http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript
return value.toFixed(precision || 0).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,")
} else {
return ""
}
}
The above works except one case:
1130.000200 becomes 1,130.000,200
but I need
1130.000200 become 1,130.000200
It seems I need negative lookbehind ?<!
, i.e. match a digit not preceded by dot, but how?
EDIT: As answered in this question, Number.prototype.toLocaleString() is a good solution for newer browsers. I need to support IE10, so leave this question as it is here.