Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to format numbers as currency strings

I would want to format a price in JavaScript. I'd like a function that takes a float as an argument and returns a string formatted like this:
"$ 2,500.00"


What's the best approach to achieve this?
by

2 Answers

aashaykumar
Take a look at the JavaScript Number object and see if it can help you.

1. toLocaleString() will format a number using location specific thousands separator.
2. toFixed() will round the number to a specific number of decimal places.
To use these at the same time the value must have its type changed back to a number because they both output a string.

Example:

Number((someNumber).toFixed(1)).toLocaleString()
sandhya6gczb
Use the following JavaScript money formatter :

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) : "");
};

Login / Signup to Answer the Question.