Skip to content

Instantly share code, notes, and snippets.

@codemile
Last active December 30, 2021 20:10
Show Gist options
  • Save codemile/47baab9075f08e1cb0ce2576de9646cf to your computer and use it in GitHub Desktop.
Save codemile/47baab9075f08e1cb0ce2576de9646cf to your computer and use it in GitHub Desktop.
Hook that formats a number as a currency using the browser's locale.
import {useMemo } from 'react';
const CODE: Record<string, string> = {
IN: 'INR',
SE: 'SEK',
GB: 'GBP',
IE: 'EUR',
CN: 'CNY',
JP: 'JPY',
US: 'USD',
KW: 'KWD'
};
const useCurrency = (value: number, locale: string = navigator.language) => {
const format = useMemo(() => {
const currency = CODE[locale.substr(-2)] || 'USD';
return new Intl.NumberFormat(locale, {
style: 'currency',
currency
});
}, [locale]);
return useMemo(() => format.format(value), [value, format]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment