Skip to content

Instantly share code, notes, and snippets.

@livingston
Created January 5, 2010 10:25
Show Gist options
  • Save livingston/269301 to your computer and use it in GitHub Desktop.
Save livingston/269301 to your computer and use it in GitHub Desktop.
number to currency formatting
/* formatCurrency.js - number to currency formatting
* @author - Livingston Samuel
*/
var formatCurrency = function (num, separator, decimal) {
var format_separator = separator || ",",
decimal_separator = decimal || ".",
parts = parseFloat(num, 10).toString().split(decimal_separator);
parts[0] = parts[0].split("").reverse().join("").match(/(\d{1,3})/g).join(format_separator).split("").reverse().join("");
if (parts.length === 1) {
parts[1] = "00";
} else {
part[1] = part[1].substr(0, 2);
}
return Number.prototype.toFixed.call(parts.join(decimal_separator), 2);
};
/* EXAMPLE USAGE
formatCurrency(100000) => 100,000.00
formatCurrency(1234567890.98) => 1,234,567,890.98
formatCurrency(1234567890.98, ".", ".") => 1.234.567.890,98
formatCurrency(1234567890.987654321) => 1,234,567,890.98
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment