Created
May 22, 2018 17:31
-
-
Save nikoheikkila/455a1a3277e4feb186c0439f9be6dba1 to your computer and use it in GitHub Desktop.
How to easily format currency in Javascript without external libraries
This file contains 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
class Payment { | |
constructor(amount, currency) { | |
this.amount = amount; | |
this.currency = currency; | |
} | |
get localeMap() { | |
return { | |
USD: "en-US", | |
EUR: "de-DE", | |
JPY: "jp-JP", | |
GBP: "en-GB" | |
}; | |
} | |
toString() { | |
const locale = this.localeMap[this.currency]; | |
const intl = new Intl.NumberFormat(locale, { | |
style: "currency", | |
currency: this.currency | |
}); | |
return intl.format(this.amount); | |
} | |
} | |
const payments = [ | |
new Payment(0, "USD"), | |
new Payment(10.50, "EUR"), | |
new Payment(15.123, "JPY"), | |
new Payment(600.314578, "GBP") | |
]; | |
/** | |
* This loop will print: | |
* $0.00 | |
* € 10.50 | |
* JP¥ 15 | |
* £ 600.31 | |
**/ | |
payments.forEach(payment => { | |
console.log(payment.toString()); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment