Skip to content

Instantly share code, notes, and snippets.

@thomasfl
Created April 13, 2016 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasfl/baba107eaf174fd7afe765d64244dada to your computer and use it in GitHub Desktop.
Save thomasfl/baba107eaf174fd7afe765d64244dada to your computer and use it in GitHub Desktop.
function formatCurrency(x, decimalPlaces, decimalSeparator, groupSeparator) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, groupSeparator);
if(parts.length > 1) {
parts[1] = parts[1].substring(0, decimalPlaces);
} else {
parts[1] = '000000000'.substring(0, decimalPlaces);
}
return parts.join(decimalSeparator);
}
function currency(amount, currencyCode) {
var decimalSeparator = ",";
var groupSeparator = " ";
var decimalPlaces = 2;
if(typeof(currencyCode) === 'undefined') {
currencyCode = '';
}
/* US, GB, Thailand and a few other places uses different separator characters */
if(currencyCode.match(/USD|GBP|THB/i) !== null) {
decimalSeparator = ".";
groupSeparator = ",";
}
var amountFormatted = formatCurrency(amount, decimalPlaces, decimalSeparator, groupSeparator);
return amountFormatted + ' ' + currencyCode;
}
console.log('Amount: ' + currency(12345) );
console.log('Amount: ' + currency(12345, 'USD') );
console.log('Amount: ' + currency(12345.6789, 'EUR') );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment