Quick and dirty number format in JavaScript
While working on a analytics system I needed a js function to convert number strings to a more readable(by humans) form.
So, inspired by the php number_format() function I came up with this.
this function defaults to the italian standard format for numbers, i.e. '.' for thousands separators and ',' for decimal separator
The function
/**
* @function jsNumberFormat
*
* @param num
* @param decPlaces
* @param thouSeparator
* @param decSeparator
* @returns {string}
*/
function jsNumberFormat(num, decPlaces, thouSeparator, decSeparator) {
decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 0 : decPlaces;
decSeparator = decSeparator == undefined ? "," : decSeparator;
thouSeparator = thouSeparator == undefined ? "." : thouSeparator;
var sign = num < 0 ? "-" : "";
var i = parseInt(num = Math.abs(+num || 0).toFixed(decPlaces)) + "";
var j = (j = i.length) > 3 ? j % 3 : 0;
return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(num - i).toFixed(decPlaces).slice(2) : "");
};
Written by Federico Brandani
Related protips
1 Response
Have you ever tried .toLocaleString()</code>? ... Example: parseInt( $nr / 1000 ).toLocaleString()</code>
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Number_format
Authors
thebrainroom
2.651K
eshva1923
1.561K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#