Posted By

TEHEK on 10/03/10


Tagged

number format jquery TextField


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

bobbym245
azipagan
verostudios
mmcachran


Format number in jQuery


 / Published in: jQuery
 

30 minutes spent on this :)

  1. $.fn.priceFormat = function (options) {
  2.  
  3. var defaultOptions = {
  4. groupSeparator: ",",
  5. decimalSeparator: "."
  6. }
  7.  
  8. // default options
  9. options = $.extend({}, defaultOptions, options);
  10.  
  11. var formatValue = function (val) {
  12. if (isNaN(val)) return 0.00;
  13. val = Number(val).toFixed(2);
  14.  
  15. var p = String(val).split(options.decimalSeparator);
  16.  
  17. var intPart = "";
  18.  
  19. for (var i = 3, t = p[0].length; i < t + 3; i+= 3) {
  20. intPart = p[0].slice(-3) + options.groupSeparator + intPart;
  21. p[0] = p[0].substring(0, t-i);
  22. console.log(intPart);
  23. }
  24.  
  25. // remove extra comma,
  26. p[0] = intPart.substring(0, intPart.length-1);
  27.  
  28. return p.join(options.decimalSeparator);
  29. }
  30.  
  31. this.each(function (i, e) {
  32. e = $(e);
  33. if ($.inArray(e.attr("tagName"), ["INPUT", "TEXTAREA"]) !== -1) {
  34. e.val(formatValue(e.val()));
  35. } else {
  36. e.text(formatValue(e.text()));
  37. }
  38. });
  39.  
  40. return this;
  41. }
  42.  
  43. $("input, span").priceFormat();

Report this snippet  

You need to login to post a comment.