Skip to content

Instantly share code, notes, and snippets.

@dmmarmol
Created September 22, 2020 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmmarmol/cf619054b762e6589ec0d0ec5852a85d to your computer and use it in GitHub Desktop.
Save dmmarmol/cf619054b762e6589ec0d0ec5852a85d to your computer and use it in GitHub Desktop.
Format Numbers
// Currency
function useCurrencyFormat() {
const { code, currency } = useCountryContext();
const options: Intl.NumberFormatOptions = {
style: 'currency',
currency,
minimumFractionDigits: 0,
maximumFractionDigits: 2,
};
return (value?: number | null) => {
const fixed = truncateToDecimals(value ?? 0, 2);
const result = new Intl.NumberFormat(code, options).format(fixed);
return result;
};
}
// Percentage
function usePercentFormat() {
const { code } = useCountryContext();
const options: Intl.NumberFormatOptions = { style: 'percent', minimumFractionDigits: 0, maximumFractionDigits: 2 };
return (value?: number | null) => {
const fixed = truncateToDecimals(value ?? 0, 2);
const result = new Intl.NumberFormat(code, options).format(fixed / 100);
return result;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment