Skip to content

Instantly share code, notes, and snippets.

@hgouveia
Created March 12, 2021 10:59
Show Gist options
  • Save hgouveia/c03ce51135c1faef6c3ca61cce83160f to your computer and use it in GitHub Desktop.
Save hgouveia/c03ce51135c1faef6c3ca61cce83160f to your computer and use it in GitHub Desktop.
number_format like is php in javascript
function number_format(value, decimals = 0, decPoint = '.', thousandsSep: string = ',') {
let formatted: string = '';
const formatter = new Intl.NumberFormat(
'de', // this will be ignored
{
style: 'currency',
currency: 'eur', // this will be ignored
minimumFractionDigits: decimals,
maximumFractionDigits: decimals
}
);
const parts = formatter.formatToParts(value);
parts.forEach(part => {
if (part.type === 'integer' || part.type === 'fraction') {
formatted += part.value;
} else if (part.type === 'group') {
formatted += thousandsSep;
} else if (part.type === 'decimal') {
formatted += decPoint;
}
});
return formatted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment