@uxf/localize
v12.0.0
Published
[](https://www.npmjs.com/package/@uxf/localize) [](https://www.npmjs.com/package/@uxf/localize) [; number/currency formatting on currency.js.
When to use
Reach for @uxf/localize when an app needs consistent, config-driven formatting across locales. You call createLocalize once with your locale map and get back a provider, hooks, components and standalone functions — all sharing a single locale context.
@uxf/ui uses the same context internally: its UiContextProvider mounts the shared provider with the app locale, so if you already wrap your app in @uxf/ui's provider you do not need to mount LocalizeProvider again — the formatters from your createLocalize will read the locale set by @uxf/ui. Mount LocalizeProvider yourself only when using @uxf/localize standalone.
Installation
yarn add @uxf/localizePeer dependencies (must be installed by the consumer):
@uxf/core,@uxf/core-reactdayjs^1.11.19react/react-dom>=18.2.0
currency.js ships as a direct dependency.
Quick start
Create the localize instance once, re-export its members, then use them across the app.
// localize.ts
import { createLocalize } from "@uxf/localize";
import cs from "@uxf/localize/locale/cs";
import en from "@uxf/localize/locale/en";
export const {
LocalizeProvider,
useLocaleConfig,
formatNumber,
formatMoney,
formatPercentage,
formatDateTime,
formatTime,
useFormatNumber,
useFormatMoney,
useFormatPercentage,
useFormatDateTime,
useFormatTime,
FormatNumber,
FormatMoney,
FormatPercentage,
FormatDateTime,
FormatTime,
} = createLocalize({ cs, en });LocalizeProvider is a plain React context provider whose value is the active locale key:
// _app.tsx
import { LocalizeProvider } from "./localize";
<LocalizeProvider value="cs">{props.children}</LocalizeProvider>;Use the hooks (they read the locale from context):
import { useFormatMoney } from "./localize";
function Price() {
const formatMoney = useFormatMoney();
return <>{formatMoney({ amount: "2000.78", currency: "CZK" })}</>; // 2 001 Kč
}Configuration
Each locale is a LocalizeConfig describing number/currency separators, currency patterns, and dayjs format strings. Seven ready-made configs ship with the package and can be imported by locale key: cs, de, en, es, fr, pl, sk (e.g. import cs from "@uxf/localize/locale/cs"). Spread a bundled config to extend or override it.
import { DateTimes, LocalizeConfig, Times } from "@uxf/localize";
const en: LocalizeConfig<DateTimes, Times> = {
number: {
thousandsSeparator: ",",
decimalSeparator: ".",
},
currency: {
thousandsSeparator: ",",
decimalSeparator: ".",
// per-currency override; `#` = amount, `!` = symbol (see Gotchas)
specialCases: {
USD: {
pattern: "#\xa0$",
negativePattern: "-$\xa0$",
},
},
},
dateTime: {
timeShort: "h:mm A",
timeFull: "h:mm:ss A",
dateShort: "M/D/YY",
dateMedium: "M/D/YYYY",
dateLong: "MMMM D. YYYY",
dateShortNoYear: "M/D",
dateLongNoYear: "MMMM D.",
dateTimeShort: "M/D/YY h:mm A",
dateTimeMedium: "M/D/YYYY h:mm A",
dateTimeLong: "MMMM D. YYYY h:mm:ss A",
},
time: {
short: "h:mm A",
long: "h:mm:ss A",
},
};
const cs: LocalizeConfig<DateTimes, Times> = {
number: {
thousandsSeparator: "\xa0",
decimalSeparator: ",",
},
currency: {
thousandsSeparator: "\xa0",
decimalSeparator: ",",
specialCases: {
CZK: {
pattern: "#\xa0Kč",
negativePattern: "-#\xa0Kč",
},
},
},
dateTime: {
timeShort: "H:mm",
timeFull: "H:mm:ss",
dateShort: "D. M. YY",
dateMedium: "D. M. YYYY",
dateLong: "D. MMMM YYYY",
dateShortNoYear: "D. M.",
dateLongNoYear: "D. MMMM",
dateTimeShort: "D. M. YY, H:mm",
dateTimeMedium: "D. M. YYYY, H:mm",
dateTimeLong: "D. MMMM YYYY, H:mm:ss",
},
time: {
short: "H:mm",
long: "H:mm:ss",
},
};Custom dateTime / time keys are supported by widening the generics: createLocalize<DateTimes | "custom", Times>({ ... }).
Formatters
All examples below assume the cs locale is active (via the provider). Outputs use a non-breaking space as the thousands separator, shown here as a normal space.
Number
import { useFormatNumber, FormatNumber } from "./localize";
const formatNumber = useFormatNumber();
formatNumber(2000.78); // 2 001 (default precision 0)
formatNumber(2000.78, { precision: 2 }); // 2 000,78
formatNumber(2000, { showPlusSign: true }); // +2 000 (+ only on positive values)
<FormatNumber value={2000.78} />;Date and time
import { useFormatDateTime, FormatDateTime } from "./localize";
const formatDateTime = useFormatDateTime();
const date = new Date("2023-07-21T07:58:35+02:00");
formatDateTime(date, "dateShort"); // 21. 7. 23
formatDateTime(date, "dateTimeMedium"); // 21. 7. 2023, 7:58
formatDateTime(date, "timeFull"); // 7:58:35
<FormatDateTime format="dateShort" value={date} />;
// the component (and the standalone function) also accept a `timeZone` prop/arg
<FormatDateTime format="dateTimeShort" timeZone="America/New_York" value={date} />;Time
Formats a TimeString ("HH:mm:ss").
import { useFormatTime, FormatTime } from "./localize";
const formatTime = useFormatTime();
formatTime("07:58:35", "short"); // 7:58
formatTime("07:58:35", "long"); // 7:58:35
<FormatTime format="short" value="07:58:35" />;Money
Takes a Money object ({ amount: string; currency: Currency }).
import { useFormatMoney, FormatMoney } from "./localize";
const formatMoney = useFormatMoney();
formatMoney({ amount: "2000.78", currency: "CZK" }); // 2 001 Kč (default precision 0)
formatMoney({ amount: "2000.78", currency: "USD" }); // 2 001 $
formatMoney({ amount: "2000.78", currency: "CZK" }, { precision: 1 }); // 2 000,8 Kč
formatMoney({ amount: "2000.78", currency: "CZK" }, { precision: 1, preferIsoCode: true }); // 2 000,8 CZK
formatMoney({ amount: "2000.78", currency: "CZK" }, { precision: 1, hideSymbol: true }); // 2 000,8
formatMoney({ amount: "500", currency: "CZK" }, { showPlusSign: true }); // +500 Kč (+ only on positive values)
<FormatMoney money={{ amount: "2000.78", currency: "CZK" }} />;Percentage
Expects a ratio and multiplies it by 100. An optional roundingType rounds to a whole percent ("nearest" → Math.round, "up" → Math.ceil, "down" → Math.floor); pass null to skip rounding and control precision via options.
import { useFormatPercentage, FormatPercentage } from "./localize";
const formatPercentage = useFormatPercentage();
formatPercentage(0.782); // 78 % (default precision 0)
formatPercentage(0.782, null, { precision: 2 }); // 78,20 %
formatPercentage(0.782, "up"); // 79 %
formatPercentage(0.788, "down"); // 78 %
formatPercentage(0.5, null, { showPlusSign: true }); // +50 % (+ only on positive values)
<FormatPercentage roundingType="up" value={0.782} />;Formatting for an explicit locale
The standalone functions take the locale as their first argument and ignore the provider context. Use them for server-side or multi-locale output.
import { formatNumber, formatDateTime, formatMoney, formatPercentage, formatTime } from "./localize";
formatNumber("cs", 2000.78); // 2 001
formatDateTime("cs", new Date("2023-07-21T07:58:35+02:00"), "dateMedium"); // 21. 7. 2023
formatMoney("cs", { amount: "2000.78", currency: "CZK" }); // 2 001 Kč
formatPercentage("cs", 0.782); // 78 %
formatTime("cs", "07:58:35", "short"); // 7:58API
Import everything from the package root: import { createLocalize } from "@uxf/localize". Locale configs are deep imports: import cs from "@uxf/localize/locale/<code>".
createLocalize(config)
createLocalize<DT extends string = DateTimes, T extends string = Times, Locales extends string = string>(
config: LocalizeConfigMap<DT, T, Locales>,
): CreateLocalizeReturn<DT, T, Locales>;Returns an object with the following members:
| Member | Signature | Notes |
| --------------------- | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| LocalizeProvider | Provider<string> | React context provider; value is the active locale key. |
| useLocaleConfig | () => LocalizeConfig<DT, T> | Returns the config for the current locale. |
| formatNumber | (locale, value, options?) => string | options: { precision?, showPlusSign? }. |
| useFormatNumber | () => (value, options?) => string | Locale from context. |
| FormatNumber | FC<{ value; options? }> | |
| formatMoney | (locale, money, options?) => string | options: { hideSymbol?, precision?, preferIsoCode?, showPlusSign? }. |
| useFormatMoney | () => (money, options?) => string | Locale from context. |
| FormatMoney | FC<{ money; options? }> | |
| formatPercentage | (locale, value, roundingType?, options?) => string | roundingType: "nearest" \| "up" \| "down" \| null; options: { precision?, showPlusSign? }. |
| useFormatPercentage | () => (value, roundingType?, options?) => string | Locale from context. |
| FormatPercentage | FC<{ value; roundingType?; options? }> | |
| formatDateTime | (locale, value, format, timeZone?) => string | value: DateValue; default timeZone is Europe/Prague. |
| useFormatDateTime | () => (value, format) => string | No timeZone param (fixed to default). |
| FormatDateTime | FC<{ value; format; timeZone? }> | |
| formatTime | (locale, value, format) => string | value: TimeString. |
| useFormatTime | () => (value, format) => string | Locale from context. |
| FormatTime | FC<{ value; format }> | |
Exported types
export type * from "./src/types" exposes, among others: LocalizeConfig, LocalizeConfigMap, CreateLocalizeReturn, DateTimes, Times, Currency, Money, TimeZone, RoundingType, FormatMoneyPattern, and the per-formatter *Options / *Function / *Component types.
_LocalizeProvider (internal)
_LocalizeProvider is exported from the package root but is internal — it is the shared global locale context, consumed by @uxf/ui's UiContextProvider. Application code should use the LocalizeProvider returned by createLocalize (it is the same context object). The two provide into the same context, so mounting either sets the locale for all formatters.
Gotchas
- Provider prop is
value, notlocale—LocalizeProvideris a raw React context provider:<LocalizeProvider value="cs">. - Default precision is
0for number, money and percentage. Pass{ precision }to show decimals; values are rounded (via currency.js), not truncated. Money.amountis a string ({ amount: "2000.78", currency: "CZK" }), not a number.formatPercentagetakes a ratio (0.782→78 %); it multiplies by 100. AroundingTyperounds to a whole percent before formatting, so decimals only appear whenroundingTypeisnull/omitted andprecisionis set.- Time zone defaults to
Europe/Praguefor date/time formatting. TheuseFormatDateTimehook is fixed to that default; to override, use the standaloneformatDateTime(locale, value, format, timeZone)or theFormatDateTimecomponent'stimeZoneprop. - Date-only strings (
"YYYY-MM-DD") are parsed as midnight in the target time zone, whileDateinstances represent a concrete instant and are shifted into that zone — the same wall-clock string can render differently depending on the input form. - Currency patterns use currency.js placeholders:
#= amount,!= symbol. Built-in defaults exist forEURandUSD;specialCasesin the config override per currency; otherwise a plain# <symbol>pattern is used, andpreferIsoCodeforces the ISO code instead of the symbol. showPlusSignonly adds+to a positive, non-zero final value (e.g.+500 Kč,+50 %). It never touches the negative sign —-is always shown regardless (handled by currency.jsnegativePattern) — and a value that rounds to0stays unsigned. MatchesIntl.NumberFormat'ssignDisplay: "exceptZero".- Separators are non-breaking spaces in some locales (e.g.
cs), so"2 001"contains, not a regular space.
Links
- npm package
- Related:
@uxf/core(Money,Currency, date types),@uxf/core-react(global context),@uxf/ui(mounts the shared locale provider).
