andrew4582

Format Number & Currency

Feb 22nd, 2012
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     var CURRENCY_US = "$";
  2.     var CURRENCY_EURO = "€";
  3.    
  4.     function testFormatNumbers() {
  5.         var number = formatNumber(1234.56)
  6.         var defcurr = formatCurrency(1234.56)
  7.         var eurocurr = formatCurrency(1234.56, CURRENCY_EURO)
  8.  
  9.         alert(number + "\n" + defcurr + "\n" + eurocurr);
  10.  
  11.     }
  12.     function formatNumber(num) {
  13.         return _formatCurrency(num);
  14.     }
  15.  
  16.     function formatCurrency(num, currencySign) {
  17.         currencySign = currencySign || "$";
  18.         return _formatCurrency(num, currencySign);
  19.     }
  20.  
  21.     function _formatCurrency(num, currencySign) {
  22.  
  23.         currencySign = currencySign || "";
  24.        
  25.         if(currencySign !== "")
  26.             currencySign = currencySign + " ";
  27.  
  28.         num = num.toString().replace(/\$|\,/g, '');
  29.         if (isNaN(num))
  30.             num = "0";
  31.  
  32.         sign = (num == (num = Math.abs(num)));
  33.         num = Math.floor(num * 100 + 0.50000000001);
  34.         cents = num % 100;
  35.         num = Math.floor(num / 100).toString();
  36.  
  37.         if (cents < 10)
  38.             cents = "";
  39.         if (cents !== "")
  40.             cents = "." + cents;
  41.  
  42.         for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
  43.             num = num.substring(0, num.length - (4 * i + 3)) + ',' +
  44.  
  45.         num.substring(num.length - (4 * i + 3));
  46.  
  47.         return (((sign) ? '' : '(') + currencySign + "" + num + cents + ((sign) ? '' : ')'));
  48.     }
Advertisement
Add Comment
Please, Sign In to add comment