View Tutorial Metadata Edit Content Revision History Add to Watchlist Add New Tutorial How to do number formatting in JavaScript

How to do number formatting in JavaScript

Number formatting in JavaScript

Sometimes, when you are working with big numbers (for example if you work with Vietnamese Dong currency) you really need to format those numbers as you don't want to have something like 1000000000 on your page.

Doing this from PHP is simple but ... what if you want to do this from JavaScript? You'll see that there is no already built function so you must write your own.

So, we want to format a number like :

  • 100 into 100
  • 1000000000 into 1,000,000,000
  • 1510.125 into 1,510.125

Here is the JavaScript function :

function numberFormat(nr){
	//remove the existing ,
	var regex = /,/g;
	nr = nr.replace(regex,'');
	//force it to be a string
	nr += '';
	//split it into 2 parts  (for numbers with decimals, ex: 125.05125)
	var x = nr.split('.');
	var p1 = x[0];
	var p2 = x.length > 1 ? '.' + x[1] : '';
	//match groups of 3 numbers (0-9) and add , between them
	regex = /(\d+)(\d{3})/;
	while (regex.test(p1)) {
		p1 = p1.replace(regex, '$1' + ',' + '$2');
	}
	//join the 2 parts and return the formatted number
	return p1 + p2;
}

and a simple HTML usage example ( live number formatting, just try to write a large number into the textbox )

<input type='text' name='price' id='price' onkeyup="this.value =
numberFormat(this.value);" />

Only plain text supported.

Optional

Required - will be kept private

Optional

 
 

Rating: (0+, 0-) In: JavaScript