Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Format Number In Javascript

DZone's Guide to

Format Number In Javascript

·
Free Resource
/**
* 
*
*
* @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;
};
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}