Created
October 7, 2018 10:20
-
-
Save koyta/a1dc9dc0b80a4edcf36a75096a469c95 to your computer and use it in GitHub Desktop.
Format money
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
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