Javascript - Manipulating currency for display and computation


/ Published in: JavaScript
Save to your folder(s)

Used to easily display or compute for prices e.g shopping cart.

Thousands separator regex based on Paul Creasey.


Copy this code and paste it in your HTML
  1. jQuery(document).ready(function($) {
  2.  
  3. $.currency = {
  4.  
  5. displayFormat: function(amount)
  6. {
  7. amount = $.currency.convert_to_decimal(amount);
  8. amount = $.currency.add_thousands_separator(amount);
  9.  
  10. return amount;
  11. },
  12.  
  13. computeFormat: function(amount)
  14. {
  15. amount = $.currency.remove_thousands_separator(amount);
  16. amount = $.currency.convert_to_decimal(amount);
  17.  
  18. return amount;
  19. },
  20.  
  21. add_thousands_separator: function(amount)
  22. {
  23. amount = String(amount);
  24. amount = amount.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
  25.  
  26. return amount;
  27. },
  28.  
  29. remove_thousands_separator: function(amount)
  30. {
  31. amount = String(amount);
  32. amount = amount.replace(/\,/g, "");
  33.  
  34. return amount;
  35. },
  36.  
  37. convert_to_decimal: function(amount)
  38. {
  39. amount = Number(amount).toFixed(2);
  40.  
  41. return amount;
  42. }
  43. };
  44. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.