Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Created May 22, 2018 17:31
Show Gist options
  • Save nikoheikkila/455a1a3277e4feb186c0439f9be6dba1 to your computer and use it in GitHub Desktop.
Save nikoheikkila/455a1a3277e4feb186c0439f9be6dba1 to your computer and use it in GitHub Desktop.
How to easily format currency in Javascript without external libraries
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