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?
Patrick Desjardins (ex Daok)'s example worked well for me. I ported over to coffeescript if anyone is interested.
There is a javascript port of the PHP function "number_format".
I find it very usefull as it is easy to use and recognisable for PHP developers.
(Comment block from the original, included below for examples & credit where due)
I found this from: accounting.js . Its very easy and perfectly fits my need.
Number.prototype.toFixed
This solution is compatible with every single major browser:
All you need is to add the currency symbol (e.g.
"$" + profits.toFixed(2)
) and you will have your amount in dollars.Custom function
If you require the use of
,
between each digit, you can use this function:Use it like so:
If you're always going to use '.' and ',', you can leave them off your method call, and the method will default them for you.
If your culture has the two symbols flipped (i.e. Europeans) and you would like to use the defaults, just paste over the following two lines in the
formatMoney
method:Custom function (ES6)
If you can use modern ECMAScript syntax (i.e. through Babel), you can use this simpler function instead:
Here's the best js money formatter I've seen:
It was re-formatted and borrowed from here: https://stackoverflow.com/a/149099/751484
You'll have to supply your own currency designator (you used $ above).
Call it like this (although note that the args default to 2, comma, & period, so you don't need to supply any args if that's your preference):
Here are some solutions, all pass the test suite, test suite and benchmark included, if you want copy and paste to test, try This Gist.
Method 0 (RegExp)
Base on https://stackoverflow.com/a/14428340/1877620, but fix if there is no decimal point.
Method 1
Method 2 (Split to Array)
Method 3 (Loop)
Usage Example
Separator
If we want custom thousands separator or decimal separator, use
replace()
:Test suite
Benchmark