Created
April 13, 2016 09:41
-
-
Save thomasfl/baba107eaf174fd7afe765d64244dada to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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