Posts with tag: format

Formatting numbers in general is something I disslike and if I have to do it I only want to do it once. So here is a small javascript function I wrote to format currencies with configurable thousand separator as well as number of decimals and what separator for decimals. It also lets you append a string to the end such as "SEK" if you wish to add some form of currency or symbol.

Here is an example of different outputs.

formatMoney('0', 2, '.', ' ', ' SEK')  > 0.00 SEK
formatMoney('', 2, '.', ' ', ' SEK')  > 0.00 SEK
formatMoney('1.23', 2, '.', ' ', ' SEK')  > 1.23 SEK
formatMoney('12345.009', 2, '.', ' ', ' SEK')  > 12 345.01 SEK
formatMoney('5234231.9', 2, '.', ',', ' USD')  > 5,234,231.90 USD


And the code itself.

var formatMoney = function(value, decimals, decimalSeparator, thousandSeparator, currencyString) {
   if (value == null || isNaN(value))
      return "";

   var decimals = isNaN(c = Math.abs(decimals)) ? 2 : decimals;
   var decimalSeparator = decimalSeparator == undefined ? "." : decimalSeparator;
   var thousandSeparator = thousandSeparator == undefined ? " " : thousandSeparator;

   var negativeSign = value < 0 ? "-" : "";

   var valueNoDecimals = String(parseInt(value = Math.abs(Number(value) || 0).toFixed(decimals)));

   var spacingStart = 0;
   if ((valueNoDecimals.length) > 3)
      spacingStart = valueNoDecimals.length % 3;

   var leadingNumber = (spacingStart ? valueNoDecimals.substr(0, spacingStart) + thousandSeparator : "");
   var separatedMiddle = valueNoDecimals.substr(spacingStart).replace(/(\d{3})(?=\d)/g, "$1" + thousandSeparator);
   var decimals = (decimals ? decimalSeparator + Math.abs(value - valueNoDecimals).toFixed(decimals).slice(2) : "");

   var result = negativeSign + leadingNumber + separatedMiddle + decimals + currencyString;
   return result.trim();
};

Here is also a fiddle with the examples above: https://jsfiddle.net/zdsv09wc/

If you're curious as to whom uses what decimal separator there is a nice chart here explaining how everyone except the EU is wrong:
http://www.statisticalconsultants.co.nz/blog/how-the-world-separates-its-decimals.html