I would like to format a price in JavaScript.
I'd like a function which takes a float
as an argument and returns a string
formatted like this:
"$ 2,500.00"
What's the best way to do this?
I would like to format a price in JavaScript.
I'd like a function which takes a float
as an argument and returns a string
formatted like this:
"$ 2,500.00"
What's the best way to do this?
There are already some great answers here. Here's another attempt, just for fun:
And some tests:
Edited: now it will handle negative numbers as well
The main part is inserting the thousand-separators, that could be done like this:
Numeral.js - a js library for easy number formatting by @adamwdraper
I use the library Globalize (from Microsoft):
It's a great project to localize numbers, currencies and dates and to have them automatically formatted the right way according to the user locale! ...and despite it should be a jQuery extension, it's currently a 100% independent library. I suggest you all to try it out! :)
Haven't seen this one. It's pretty concise and easy to understand.
Here is a version with more options in the final output to allow formatting different currencies in different locality formats.
Below is the Patrick Desjardins (alias Daok) code with a bit of comments added and some minor changes:
and here some tests:
The minor changes are:
moved a bit the
Math.abs(decimals)
to be done only when is notNaN
.decimal_sep
can not be empty string anymore (a some sort of decimal separator is a MUST)we use
typeof thousands_sep === 'undefined'
as suggested in How best to determine if an argument is not sent to the JavaScript function(+n || 0)
is not needed becausethis
is aNumber
object