Thursday, May 14, 2015

Format mata uang (currency) dengan Javascript

Bagi yang tidak terlalu suka menggunakan javascript framework mem-format mata uang bisa dilakukan dengan cara sebagai berikut.


/* 
decimal_sep: character used as deciaml separtor, it defaults to '.' when omitted
thousands_sep: char used as thousands separator, it defaults to ',' when omitted
*/
Number.prototype.toMoney = function(decimals, decimal_sep, thousands_sep)
{ 
   var n = this,
   c = isNaN(decimals) ? 2 : Math.abs(decimals), //if decimal is zero we must take it, it means user does not want to show any decimal
   d = decimal_sep || '.', //if no decimal separator is passed we use the dot as default decimal separator (we MUST use a decimal separator)

   /*
   according to [http://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function]
   the fastest way to check for not defined parameter is to use typeof value === 'undefined' 
   rather than doing value === undefined.
   */   
   t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, //if you don't want to use a thousands separator you can pass empty string as thousands_sep value

   sign = (n < 0) ? '-' : '',

   //extracting the absolute value of the integer part of the number and converting to string
   i = parseInt(n = Math.abs(n).toFixed(c)) + '', 

   j = ((j = i.length) > 3) ? j % 3 : 0; 
   return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); 
}


Untuk penyesuaian format bisa dilakukan sendiri ya :D.

Nah, jika ingin lebih praktis banyak juga library yang sudah dibuat para orang budiman yang berbaik hati mau berbagi. Salah satu contohnya adalah accounting.js.
Penggunaannya cukup mudah berikut beberapa contohnya.

// Standard usage and parameters (returns string):
accounting.formatMoney(number,[symbol = "$"],[precision = 2],[thousand = ","],[decimal = "."],[format = "%s%v"])

// Second parameter can be an object:
accounting.formatMoney(number, [options])

// Available fields in options object, matching `settings.currency`:
var options = {
 symbol : "$",
 decimal : ".",
 thousand: ",",
 precision : 2,
 format: "%s%v"
};

// Example usage:
accounting.formatMoney(12345678); // $12,345,678.00
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
accounting.formatMoney(-500000, "£ ", 0); // £ -500,000

// Example usage with options object:
accounting.formatMoney(5318008, {
 symbol: "GBP",
 precision: 0,
 thousand: "·",
 format: {
  pos : "%s %v",
  neg : "%s (%v)",
  zero: "%s  --"
 }
});

// Will recursively format an array of values:
accounting.formatMoney([123, 456, [78, 9]], "$", 0); // ["$123", "$456", ["$78", "$9"]]

Gitu aja :D. Sampai jumpa di lain post. Thanks

Oh iya lupa kasi referensinya : http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript dan http://openexchangerates.github.io/accounting.js