Devil Raily
Devil Raily

Reputation: 562

Format number to dollar

I have a number 5850 and I need it to be formatted in dollar.

Example 1:

5850 => $58.50

Example 2:

9280 => $92.80

I' am using the following function:

Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) {
    var n = this,
        decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
        decSeparator = decSeparator == undefined ? "." : decSeparator,
        thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
        sign = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};

The above function gives me $5,850.00.

Upvotes: 0

Views: 264

Answers (3)

James Eames
James Eames

Reputation: 41

I think it would be easier to just use a library that could handle it for you. I use currencyFormatter.js (https://osrec.github.io/currencyFormatter.js/) - give it a try. Works on all browsers and pretty light-weight. It'll also add the currency symbols for you, and can format according to a specified locale:

OSREC.CurrencyFormatter.format(2534234, { currency: 'INR' }); 
// Returns ₹ 25,34,234.00

OSREC.CurrencyFormatter.format(2534234, { currency: 'EUR' }); 
// Returns 2.534.234,00 €

OSREC.CurrencyFormatter.format(2534234, { currency: 'EUR', locale: 'fr' }); 
// Returns 2 534 234,00 €

Upvotes: 1

Matt
Matt

Reputation: 324

If you don't care much for numbers longer than 4 digits you can use something like

function dollars(n) {
  return (n+"").replace(/(\d{0,2})(\d{2}).*/, "$$$1.$2")
}

Upvotes: 0

Indra Uprade
Indra Uprade

Reputation: 808

You can still use the same method just by tweaking it little bit like below:

Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) {
    var n = this,
        decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
        decSeparator = decSeparator == undefined ? "." : decSeparator,
        thouSeparator = '',
        thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
        sign = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};

Upvotes: 1

Related Questions