Skip to content

Instantly share code, notes, and snippets.

@koyta
Created October 7, 2018 10:20
Show Gist options
  • Save koyta/a1dc9dc0b80a4edcf36a75096a469c95 to your computer and use it in GitHub Desktop.
Save koyta/a1dc9dc0b80a4edcf36a75096a469c95 to your computer and use it in GitHub Desktop.
Format money
function formatMoney(amount, decimalCount = 2, decimal = '.', thousands = ',') {
try {
decimalCount = Math.abs(decimalCount);
decimalCount = isNaN(decimalCount) ? 2 : decimalCount;
const negativeSign = amount < 0 ? '-' : '';
let i = parseInt((amount = Math.abs(Number(amount) || 0).toFixed(decimalCount))).toString();
let j = i.length > 3 ? i.length % 3 : 0;
return (
negativeSign +
(j ? i.substr(0, j) + thousands : '') +
i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousands) +
(decimalCount
? decimal +
Math.abs(amount - i)
.toFixed(decimalCount)
.slice(2)
: '')
);
} catch (e) {
console.error(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment