Skip to content

Instantly share code, notes, and snippets.

@xxzefgh
Last active October 7, 2020 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xxzefgh/9b79a985d9c34ccadfd2fb8bc36e237d to your computer and use it in GitHub Desktop.
Save xxzefgh/9b79a985d9c34ccadfd2fb8bc36e237d to your computer and use it in GitHub Desktop.
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