Last Updated: April 02, 2020
·
1.562K
· eshva1923

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) : "");
};

1 Response
Add your response

Have you ever tried .toLocaleString()</code>? ... Example: parseInt( $nr / 1000 ).toLocaleString()</code>

over 1 year ago ·