• CMSnpm version

    • Overview
    • ContentBuilder
    • InviteUserForm
    • LoginForm
    • RenewPasswordForm
  • UInpm version

    • Overview
    • Accordion
    • AlertBubble
    • AnnouncementBar
    • Avatar
    • AvatarFileInput
    • Badge
    • Button
    • ButtonGroup
    • ButtonList
    • Calendar
    • Checkbox
    • CheckboxButton
    • CheckboxInput
    • CheckboxList
    • Chip
    • ColorRadio
    • ColorRadioGroup
    • Combobox
    • DatePicker
    • DatePickerInput
    • DateRangePicker
    • DateRangePickerInput
    • DatetimePicker
    • DatetimePickerInput
    • Dialog
    • Dropdown
    • Dropzone
    • ErrorMessage
    • FileInput
    • FlashMessages
    • FormComponent
    • Icon
    • IconButton
    • ImageGallery
    • InfoBox
    • Input
    • Label
    • Layout
    • Lightbox
    • ListItem
    • Loader
    • Lozenge
    • Menu
    • Message
    • Modal
    • ✅ ModalDialog
    • ✅ ModalHeader
    • MultiCombobox
    • MultiSelect
    • Pagination
    • Paper
    • Popover
    • Radio
    • RadioGroup
    • RasterImage
    • Select
    • ✅ Tabs
    • TextInput
    • TextLink
    • Textarea
    • TimePicker
    • TimePickerInput
    • Toggle
    • Tooltip
    • Typography
  • Formnpm version

    • Overview
    • AvatarFileInput
    • CheckboxButton
    • CheckboxInput
    • CheckboxList
    • ColorRadioGroup
    • Combobox
    • DatePickerInput
    • DateRangePickerInput
    • DatetimePickerInput
    • Dropzone
    • FileInput
    • Form
    • FormRenderer
    • GpsInput
    • MoneyInput
    • MultiCombobox
    • MultiSelect
    • NumberInput
    • PasswordInput
    • RadioGroup
    • Select
    • TextInput
    • Textarea
    • TimePickerInput
    • Toggle
  • DataGridnpm version

    • Overview
    • DataGrid
    • DataGridCustomExample
    • ExportButton
    • FilterList
    • Filters
    • FiltersButton
    • FulltextInput
    • HiddenColumns
    • HiddenColumnsButton
    • Pagination
    • RowCounts
    • RowsPerPageSelect
    • SelectedRowsToolbar
    • TableV2
    • ToolbarControl
    • ToolbarCustoms
    • ToolbarTabs
  • Wysiwygnpm version

    • Overview
  • Resizernpm version

    • Overview
  • Routernpm version

    • Overview
  • Corenpm version

    • Overview
  • Core-Reactnpm version

    • Overview
  • Stylesnpm version

    • Overview
  • Localizenpm version

    • Overview
  • Analyticsnpm version

    • Overview
  • Datepickernpm version

    • Overview
  • Icons-generatornpm version

    • Overview
  • Smart-addressnpm version

    • Overview
  • E2Enpm version

    • Overview
  • E2E-Playwrightnpm version

    • Overview

@uxf/localize

npm size quality license

Locale-aware formatting of numbers, currency amounts, percentages, dates and times, driven by per-locale config objects. Date/time handling is built on dayjs (UTC + timezone plugins); 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/localize

Peer dependencies (must be installed by the consumer):

  • @uxf/core, @uxf/core-react
  • dayjs ^1.11.19
  • react / 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 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 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 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:58

API

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? }.
useFormatNumber () => (value, options?) => string Locale from context.
FormatNumber FC<{ value; options? }>
formatMoney (locale, money, options?) => string options: { hideSymbol?, precision?, preferIsoCode? }.
useFormatMoney () => (money, options?) => string Locale from context.
FormatMoney FC<{ money; options? }>
formatPercentage (locale, value, roundingType?, options?) => string roundingType: "nearest" | "up" | "down" | null.
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, not locale — LocalizeProvider is a raw React context provider: <LocalizeProvider value="cs">.
  • Default precision is 0 for number, money and percentage. Pass { precision } to show decimals; values are rounded (via currency.js), not truncated.
  • Money.amount is a string ({ amount: "2000.78", currency: "CZK" }), not a number.
  • formatPercentage takes a ratio (0.782 → 78 %); it multiplies by 100. A roundingType rounds to a whole percent before formatting, so decimals only appear when roundingType is null/omitted and precision is set.
  • Time zone defaults to Europe/Prague for date/time formatting. The useFormatDateTime hook is fixed to that default; to override, use the standalone formatDateTime(locale, value, format, timeZone) or the FormatDateTime component's timeZone prop.
  • Date-only strings ("YYYY-MM-DD") are parsed as midnight in the target time zone, while Date instances 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 for EUR and USD; specialCases in the config override per currency; otherwise a plain # <symbol> pattern is used, and preferIsoCode forces the ISO code instead of the symbol.
  • 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).

FormatDateTime example:

By date string 2024-10-24:24. October 2024, 0:00:00
By datetime string 2024-10-24T12:46:26+02:00:24. October 2024, 12:46:26
By new Date() new Date("2024-10-24T12:46:26+02:00"):24. October 2024, 12:46:26
By datetime string, timezone: Pacific/Auckland 2024-10-24T12:46:26+02:00:24. October 2024, 23:46:26