Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Number Formatting With Commas

Tags:

I'm trying to format numbers so they have commas between every 3 numbers. It is very glitchy however and doesn't work once it gets to 8 numbers. I've put all the code in a jsfiddle below:

function commaSeparateNumber(val){     val = val.replace(',', '');     var array = val.split('');     var index = -3;     while (array.length + index > 0) {         array.splice(index, 0, ',');         // Decrement by 4 since we just added another unit to the array.         index -= 4;     }     return array.join(''); };      $(document).on('keyup', '.test', function() {     var value = $(this).val();     value = commaSeparateNumber(value);     $(this).val(value); }); 

http://jsfiddle.net/R8JrF/

Any help is appreciated!

like image 390
MrGrinst Avatar asked Jun 03 '13 18:06

MrGrinst


People also ask

How do you format numbers in JavaScript?

JavaScript numbers can be formatted in different ways like commas, currency, etc. You can use the toFixed() method to format the number with decimal points, and the toLocaleString() method to format the number with commas and Intl. NumberFormat() method to format the number with currency.

How can I format a string number to have commas?

For format String "%,. 2f" means separate digit groups with commas and ".

How do you put a comma in input type numbers?

You can use type="text" and then add commas to the number in the onchange event.

How do I display large numbers with commas in HTML?

There's a simpler syntax for toLocaleString: Number(x). toLocaleString();


2 Answers

I improvised the answer in the comment. What you would need is the below code only. Check this out and also the fiddle:

$(document).on('keyup', '.test', function() {     var x = $(this).val();     $(this).val(x.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")); }); 

Fiddle: http://jsfiddle.net/praveenscience/R8JrF/1/

The reason why it didn't work was, once you make changes, you need to remove all the commas, and do the formatting again, which was not done in the OP's code as well as the other answer code.

like image 104
Praveen Kumar Purushothaman Avatar answered Oct 01 '22 01:10

Praveen Kumar Purushothaman


Use Number.prototype.toLocaleString(); check here

var no = 3456; no.toLocaleString();  

Gives 3,456

like image 37
optimistanoop Avatar answered Sep 30 '22 23:09

optimistanoop