DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Format Number In Javascript

06.18.2010
| 3475 views |
  • submit to reddit
        /**
* 
*
*
* @example: 
*   format(12345.6789); //12345,67
*   format(12345.6789, {point:'.'}); //12345.67
*   format(12345.6789,{suffix:'€'}); //12345,67€
*   format(12345.6789,{point:'.',prefix:'$ '}); //$ 12345.67
*/
var format = function(num, options)) {
	options.point=options.point||',';
	options.group=options.group||' ';
	options.places=options.places||2;
	options.suffix=options.suffix||'';
	options.prefix=options.prefix||'';

	regex = /(\d+)(\d{3})/;
	result = ((isNaN(num) ? 0 : Math.abs(num)).toFixed(options.places)) + '';

	for (result = result.replace('.', options.point); regex.test(result) && options.group; result=result.replace(regex, '$1'+options.group+'$2')) {};
	return (num < 0 ? '-' : '') + options.prefix + result + options.suffix;
};