andrew4582

formatCurrency

Feb 6th, 2012
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function formatCurrency(num) {
  2.     num = num.toString().replace(/\$|\,/g, '');
  3.     if (isNaN(num))
  4.         num = "0";
  5.    
  6.     sign = (num == (num = Math.abs(num)));
  7.     num = Math.floor(num * 100 + 0.50000000001);
  8.     cents = num % 100;
  9.     num = Math.floor(num / 100).toString();
  10.    
  11.     if (cents < 10)
  12.         cents = "0" + cents;
  13.    
  14.     for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
  15.         num = num.substring(0, num.length - (4 * i + 3)) + ',' +
  16.  
  17.     num.substring(num.length - (4 * i + 3));
  18.  
  19.     return (((sign) ? '' : '(') + '$' + num + '.' + cents + ((sign) ? '' : ')') );
  20.  
  21.     // return (((sign) ? '' : '-') + '$' + num + '.' + cents);
  22. }
Advertisement
Add Comment
Please, Sign In to add comment