Entrepreneur, Musician, Traveler, Founder of Open Exchange Rates

Format and un-format money/currency in JavaScript

Here’s a couple of simple JavaScript money-formattin’ snippets I use all the time where currencies are handled.

The code in this post has been expanded into accounting.js, a tiny JS library with some handy methods for number, money and currency formatting. Check it out!

Also: need to do real-time currency conversion in your apps and sites? Take a look at the Open Exchange Rates API!

The first is a function to format money/currency in JavaScript, turning an integer or float into a formatted string (with customisable decimal precision, currency symbol, decimal- and thousands-separators).

The second is a regular expression that removes currency formatting, so that parseInt / parseFloat can be used to extract the value from a currency-formatted string.

JavaScript Money Format

This extends the native Number object, so that all new numbers (integers/floats) can have the moneyformat() method called on them. If you prefer not to extend JavaScript’s native Number object for any reason, this also works fine as a standalone function or a library method (examples below.)

Currency to number – removing money formatting:

Say you have a currency-formatted string, eg. "HK$ -100,000.50" and you want to get the value from that, removing all currency formatting and thousand-separators. Default methods won’t get you very far: parseInt and parseFloat both return NaN (“not a number”, as the string had non-numeric characters in it.)

This one says: If symbol is anything except undefined, use it; if not, use the default of "$". The !== check is strict and checks the variable type (which means that symbol can be an empty string, "", but needs to be explicitly defined as such.)

thousand = thousand || ",";

This one says: Use thousand if it’s truthy, or anything that coerces to a boolean true (not falsey, which would include null, undefined, "" and 0) – otherwise, use ",". Logically this makes sure that thousands are always separated, otherwise there’d be no sense using this method, but you can separate them with space or point (" " or ".")

can you tell me if this has the capability as well of extracting only the symbol (in plaintext or as a symbol ie GBP or the actual symbol) as well as whether its at the beginning or end of the string? If so please advise how, I didn’t see that capability here.

I wrote a simple code (angularjs service) that can parse a currency string without any prior knowledge about it and then can take a new number and rebuild a string with the same format and currency.
Hopefully it can help someone:http://plnkr.co/edit/UXn5doViqNnyn13I4tNQ?p=preview