Javascript Currency

Presents a locale formatted currency string, including a locale'd negation operator (will work either at end or beginning of the number), locale'd thousands seperators, and a possibly localed decimal place symbol (depending on the implementation of Number.toFixed()).

There are two paramters to the new prototype function - the currency symbol, and the number of decimal places to show.

NB this will fail in locales where numbers are written right-to-left due to the string concatenation.

Number.prototype.toCurrencyString = function(prefix, dp) { if ('undefined' === typeof dp) dp = 2; var r = Math.abs(this % 1), q = Math.floor(Math.abs(this)) + parseInt(r.toFixed(dp)), s = (this < 0 ?(-1).toLocaleString() : '1'); return s.replace('1', prefix + q.toLocaleString() + r.toFixed(dp).substr(1)); } var x = 5; alert(x.toCurrencyString('$'));
Test Area =