Formatting currency in Javascript

A post by Peter Hollows about javascript. Posted 9 months ago.

I’ve been hunting for something like Rails’ number_to_currency for Javascript that’d give me a delimited output with precision in cents.

Most of what I found didn’t work well so I rolled my own. The code is fairly simple compared to other alternatives and can be easily modified to work with other currencies or dollar amounts.

// Examples
 433495.toCurrency(); // gives  $4,334.95
-433495.toCurrency(); // gives -$4,334.95

Implementation

Number.prototype.toCurrency = function() {
  var match, cents, dollars, result;

  match = (this / 100).toString().match(/^-?(\d+)(\.\d+)?$/);
  if (!match) return;

  cents = match[2] ? (match[2] + '00').substr(1, 2) : '00';
  dollars = match[1].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,');

  result = '$' + dollars + '.' + cents;
  if (this < 0) { result = '-' + result };
  return result;
};