Skip to content

Instantly share code, notes, and snippets.

@DanWebb
Last active July 19, 2017 14:12
Show Gist options
  • Save DanWebb/266b9d33214072c54e71 to your computer and use it in GitHub Desktop.
Save DanWebb/266b9d33214072c54e71 to your computer and use it in GitHub Desktop.
Format a value to display as a monetary value
export default (amount, currency) => {
const currencies = {
AFN: '؋',
ARS: '$',
AWG: 'ƒ',
AUD: '$',
AZN: '₼',
BSD: '$',
BBD: '$',
BYR: 'p.',
BZD: 'BZ$',
BMD: '$',
BOB: 'Bs.',
BAM: 'KM',
BWP: 'P',
BGN: 'лв',
BRL: 'R$',
BND: '$',
KHR: '៛',
CAD: '$',
KYD: '$',
CLP: '$',
CNY: '¥',
COP: '$',
CRC: '₡',
HRK: 'kn',
CUP: '₱',
CZK: 'Kč',
DKK: 'kr',
DOP: 'RD$',
XCD: '$',
EGP: '£',
SVC: '$',
EEK: 'kr',
EUR: '€',
FKP: '£',
FJD: '$',
GHC: '¢',
GIP: '£',
GTQ: 'Q',
GGP: '£',
GYD: '$',
HNL: 'L',
HKD: '$',
HUF: 'Ft',
ISK: 'kr',
INR: '₹',
IDR: 'Rp',
IRR: '﷼',
IMP: '£',
ILS: '₪',
JMD: 'J$',
JPY: '¥',
JEP: '£',
KES: 'KSh',
KZT: 'лв',
KPW: '₩',
KRW: '₩',
KGS: 'лв',
LAK: '₭',
LVL: 'Ls',
LBP: '£',
LRD: '$',
LTL: 'Lt',
MKD: 'ден',
MYR: 'RM',
MUR: '₨',
MXN: '$',
MNT: '₮',
MZN: 'MT',
NAD: '$',
NPR: '₨',
ANG: 'ƒ',
NZD: '$',
NIO: 'C$',
NGN: '₦',
NOK: 'kr',
OMR: '﷼',
PKR: '₨',
PAB: 'B/.',
PYG: 'Gs',
PEN: 'S/.',
PHP: '₱',
PLN: 'zł',
QAR: '﷼',
RON: 'lei',
RUB: '₽',
SHP: '£',
SAR: '﷼',
RSD: 'Дин.',
SCR: '₨',
SGD: '$',
SBD: '$',
SOS: 'S',
ZAR: 'R',
LKR: '₨',
SEK: 'kr',
SRD: '$',
SYP: '£',
TZS: 'TSh',
TWD: 'NT$',
THB: '฿',
TTD: 'TT$',
TRY: '',
TRL: '₤',
TVD: '$',
UGX: 'USh',
UAH: '₴',
GBP: '£',
USD: '$',
UYU: '$U',
UZS: 'лв',
VEF: 'Bs',
VND: '₫',
YER: '﷼',
ZWD: 'Z$'
};
const roundNumber = (num, dec) => Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
if (amount) {
// Make sure "amount" is an int
if (String(amount).indexOf('.') > -1) {
amount = Number(amount) * 100;
}
// Round the amount to a maximum of 8 decimal places
amount = roundNumber((amount / 100), 8);
// Make sure there's atleast two dicimal places
amount = amount.toFixed(2);
} else {
amount = 0.00;
}
if (!currency) {
return amount;
}
return currencies[currency] ? `${currencies[currency]}${amount}` : `${amount} ${currency}`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment