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?
Ok, based on what you said, i'm using this:
I'm open to improvement suggestions (i'd prefer not to include YUI just to do this :-) ) I already know I should be detecting the "." instead of just using it as the decimal separator...
I think what you want is
f.nettotal.value = "$" + showValue.toFixed(2);
From WillMaster.
Take a look at the JavaScript Number object and see if it can help you.
toLocaleString()
will format a number using location specific thousands separator.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:
Patrick Desjardins' answer looks good, but I prefer my javascript simple. Here's a function I just wrote to take a number in and return it in currency format (minus the dollar sign)
I suggest the NumberFormat class from Google Visualization API.
You can do something like this:
I hope it helps.