Last active
October 7, 2020 13:18
-
-
Save xxzefgh/9b79a985d9c34ccadfd2fb8bc36e237d to your computer and use it in GitHub Desktop.
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(value: any, thousandSeparator: string | false = false, fractionDigits = 2): string { | |
let number = Number(value); | |
if (isNaN(number)) { | |
number = 0; | |
} | |
// Number#toFixed will throw runtime exception if fractionDigits isn't within 0-100 range | |
if (fractionDigits < 0 || fractionDigits > 100) { | |
fractionDigits = 0; | |
} | |
const [integer, fraction] = number.toFixed(fractionDigits + 1).slice(0, -1).split('.'); | |
const formattedInteger = thousandSeparator ? integer.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator) : integer; | |
return formattedInteger + (fractionDigits > 0 ? '.' + fraction : ''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment