Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add commas to a number in jQuery

I have these numbers

10999 and 8094 and 456

And all i want to do is add a comma in the right place if it needs it so it looks like this

10,999 and 8,094 and 456

These are all within a p tag like this <p class="points">10999</p> etc.

Can it be done?

I've attempted it here with the help of other posts http://jsfiddle.net/pdWTU/1/ but can't seem to get it to work

Thanks

Jamie

UPDATE

Messed around a bit and managed to figure it out here http://jsfiddle.net/W5jwY/1/

Going to look at the new Globalization plugin for a better way of doing it

Thanks

Jamie

like image 639
Jamie Taylor Avatar asked Oct 07 '10 15:10

Jamie Taylor


People also ask

How do you put commas in numbers?

What are the rules for using commas? First comma is placed three digits from the right of the number to form thousands, second comma is placed next two digits from the right of the number, to mark lakhs and third comma is placed after another next two digits from the right to mark crore, in Indian system of numeration.

How Split comma Separated Values in jquery?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc.

How do you use commas when typing?

On English PC and Mac keyboards, the comma is on the same key as the less than symbol. Pressing the , key with no other key creates the comma symbol.


1 Answers

Works on all browsers, this is all you need.

  function commaSeparateNumber(val){     while (/(\d+)(\d{3})/.test(val.toString())){       val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');     }     return val;   } 

Wrote this to be compact, and to the point, thanks to regex. This is straight JS, but you can use it in your jQuery like so:

$('#elementID').html(commaSeparateNumber(1234567890)); 

or

$('#inputID').val(commaSeparateNumber(1234567890)); 

However, if you require something cleaner, with flexibility. The below code will fix decimals correctly, remove leading zeros, and can be used limitlessly. Thanks to @baacke in the comments.

  function commaSeparateNumber(val){    val = val.toString().replace(/,/g, ''); //remove existing commas first    var valRZ = val.replace(/^0+/, ''); //remove leading zeros, optional    var valSplit = valRZ.split('.'); //then separate decimals         while (/(\d+)(\d{3})/.test(valSplit[0].toString())){     valSplit[0] = valSplit[0].toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');    }     if(valSplit.length == 2){ //if there were decimals     val = valSplit[0] + "." + valSplit[1]; //add decimals back    }else{     val = valSplit[0]; }     return val;   } 

And in your jQuery, use like so:

$('.your-element').each(function(){   $(this).html(commaSeparateNumber($(this).html())); }); 

Here's the jsFiddle.

like image 76
Timothy Perez Avatar answered Sep 21 '22 01:09

Timothy Perez