0

I need a script that simply formats a value (eg 4567643) to (4,567,643). No currency symbol or decimals are required. I have found several scripts including this one:

http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx

But it's very heavy for what I need, I imagine something very light could do what I need (and hopefully not require a separate plugin.)

Any help would be much appreciated.

1475293
  • 47
  • 1
  • 8
  • If you *just* want to add commas to numbers see [here](http://stackoverflow.com/questions/721304/insert-commas-into-number-string). (specifically, `var formattedNum = unformattedNum.toString().replace(/(\d)(?=(\d\d\d)+$)/g, "$1,");`). – Matt Jun 25 '12 at 10:23
  • Thanks for the link. This only seems to provide examples in AS3 and java though. I'm new to jquery so don't know how to implement this. – 1475293 Jun 25 '12 at 10:44
  • I provided it for you; `var formattedNum = unformattedNum.toString().replace(/(\d)(?=(\d\d\d)+$)/g, "$1,");` – Matt Jun 25 '12 at 10:47
  • Sorry for the novice questions, but I don't understand where to put that. Does that need to be in a function or something? And then apply it to specific text with a class? Thanks for your help. – 1475293 Jun 25 '12 at 10:54
  • The snippet assumes the unformatted number is stored in a variable called `unformattedNum`. It then formats the number and puts it in a `formattedNum` variable. You can put it wherever you want as long as you've got the num to format it. If you need to grab the number from a text box or something use `var unformattedNum = $('#your_text_box_id').val()`; see [jQuery selectors](http://api.jquery.com/category/selectors/) and [`jQuery.val()`](http://api.jquery.com/val) for more info. – Matt Jun 25 '12 at 10:59

1 Answers1

0

Here's the code I ended up with for anybody else that may find it useful:

$.fn.digits = function(){ 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
}

$(".currency").digits();

Where a div with class 'currency' contains the number you want to format.

1475293
  • 47
  • 1
  • 8