The /format/ package provides number, date, and miscellaneous formatting functions used
throughout Hoist applications. Given Hoist's focus on financial and enterprise applications,
number formatting is especially rich β supporting ledger-style accounting format, sign-based
color coding, automatic precision scaling, and labeled units (thousands, millions, billions).
The package exports three categories of tools for each data type:
-
Formatter functions (e.g.
fmtNumber) - take a value and options, return formatted output. Use these for ad-hoc, inline formatting in component render methods and business logic. -
Renderer factories (e.g.
numberRenderer) - take options only and return a pre-configured function suitable for use as a grid columnrenderer. Use these for grid columns that need markup, and for other declarative configurations. -
Text renderer factories (e.g.
numberTextRenderer) - take options only and return a function that always returns a string, for a grid columntextRenderer. Prefer these for grid columns that show text.
/format/
βββ FormatNumber.ts # Number formatting: fmtNumber, fmtPercent, fmtMillions, etc.
βββ FormatDate.ts # Date formatting: fmtDate, fmtDateTime, fmtCompactDate, etc.
βββ RenderNumber.ts # Number cell factories: numberRenderer, numberTextRenderer, etc.
βββ RenderDate.ts # Date cell factories: dateRenderer, dateTextRenderer, etc.
βββ FormatMisc.ts # Utilities: fmtSpan, fmtJson, capitalizeWords
βββ FormatUtils.ts # createRenderer() - the renderer factory utility, and TextRenderer
βββ impl/
βββ Utils.ts # Internal helpers (saveOriginal, ROUNDED_ZERO)
This is a key distinction for working with the format package.
Formatter functions take a value and optional options, returning formatted output directly. Use them in render methods, tooltips, and anywhere you have a value in hand:
import {fmtNumber, fmtPercent, fmtDate} from '@xh/hoist/format';
// Inline formatting in a component
span(fmtNumber(totalRevenue, {precision: 0, prefix: '$'}))
// In a tooltip or label
const label = `Change: ${fmtPercent(pctChange, {precision: 0, colorSpec: true, withSignGlyph: true})}`;
// Date formatting
const dateStr = fmtDate(trade.settleDate);Renderer factories take options only and return a pre-configured function (value) => formattedOutput.
This curried pattern is designed for grid column renderer props and other declarative configs
where the formatting options are known at definition time but the value arrives later. For a grid
column that shows only text, prefer the text renderer factories below.
import {numberRenderer, dateRenderer, percentRenderer} from '@xh/hoist/format';
// In a grid column definition β renderer is called per-row with each cell value
const columns = [
{field: 'tradeDate', renderer: dateRenderer()},
{field: 'quantity', renderer: numberRenderer({precision: 0, ledger: true})},
{field: 'price', renderer: numberRenderer({precision: 2})},
{field: 'pnl', renderer: numberRenderer({precision: 0, ledger: true, colorSpec: true})},
{field: 'change', renderer: percentRenderer({precision: 1, colorSpec: true, withSignGlyph: true})}
];Every formatter function has a corresponding renderer factory:
| Formatter | Renderer Factory |
|---|---|
fmtNumber |
numberRenderer |
fmtThousands |
thousandsRenderer |
fmtMillions |
millionsRenderer |
fmtBillions |
billionsRenderer |
fmtQuantity |
quantityRenderer |
fmtPrice |
priceRenderer |
fmtPercent |
percentRenderer |
fmtDate |
dateRenderer |
fmtDateTime |
dateTimeRenderer |
fmtDateTimeSec |
dateTimeSecRenderer |
fmtTime |
timeRenderer |
fmtCompactDate |
compactDateRenderer |
Renderer factories are created via the createRenderer() utility, which simply curries the
corresponding formatter:
// createRenderer(fmtNumber) produces:
// (opts?) => (value) => fmtNumber(value, opts)
export const numberRenderer = createRenderer(fmtNumber);Text renderer factories take options only, as renderer factories do, but the function they
return always returns a string. Use it as a grid column's textRenderer. ag-Grid writes the
text into the cell, with no React component per cell, which makes this the cheaper path for numbers
and dates in grids. Every renderer factory above has a text renderer factory with the same prefix,
such as numberTextRenderer and dateTextRenderer. The built-in number and date column specs in
@xh/hoist/cmp/grid use them.
import {numberTextRenderer, millionsTextRenderer, dateTextRenderer} from '@xh/hoist/format';
columns: [
{field: 'pnl', textRenderer: numberTextRenderer({precision: 0, ledger: true, colorSpec: true})},
{field: 'volume', textRenderer: millionsTextRenderer({precision: 1, label: true})},
{field: 'tradeDate', textRenderer: dateTextRenderer('MMM D')}
]A text renderer factory takes the options of its renderer counterpart, less those that need markup:
| Option | In a text renderer factory |
|---|---|
colorSpec |
Class names only. Rules on the text renderer color the whole cell. Keep numberRenderer for inline styles |
ledger |
Supported. With forceLedgerAlign (the default), a cell class reserves the width of a ) on values without one |
label |
Appended as plain text, with no xh-units-label span. labelCls is not supported |
nullDisplay, zeroDisplay |
Strings only |
tooltip |
Not supported. Set Column.tooltip instead, for example to v => fmtNumberTooltip(v) |
withSignGlyph, asHtml |
Not supported |
The option types enforce this table. A markup option or an element display value fails to compile, also through a variable or a spread of shared renderer options.
The colorSpec and ledger rules ride on the returned function as cellClassRules. Column applies
them beneath its own cellClassRules, so a column rule for the same class name wins.
Number formatting is the most heavily used part of this package. The core function fmtNumber
powers all number formatters, with convenience wrappers for common financial use cases.
The primary number formatting function. All other number formatters delegate to it.
fmtNumber(1234567) // "1,234,567"
fmtNumber(0.0456) // "0.0456"
fmtNumber(1234.5, {
precision: 2,
prefix: '$'
}) // "$1,234.50"| Option | Type | Default | Description |
|---|---|---|---|
precision |
0-12 | 'auto' |
'auto' |
Decimal places. 'auto' adjusts based on value magnitude |
zeroPad |
boolean | 0-12 |
true when precision is fixed |
Pad with trailing zeros. A number specifies minimum zeros without padding to full precision |
withCommas |
boolean |
true |
Include thousands separators |
omitFourDigitComma |
boolean |
false |
Skip comma for exactly 4-digit whole numbers (e.g. 1500 vs 1,500) |
ledger |
boolean |
false |
Wrap negative values in parentheses instead of showing minus sign |
forceLedgerAlign |
boolean |
true |
Add invisible placeholder after positive ledger values so digits align vertically in columns |
colorSpec |
boolean | ColorSpec |
false |
Color output by sign. true for default red/green/grey classes |
withPlusSign |
boolean |
false |
Prepend + to positive values |
withSignGlyph |
boolean |
false |
Prepend β΄/βΎ arrow glyphs by sign |
prefix |
string |
null |
String to prepend (e.g. '$'), placed between sign and digits |
label |
string | boolean |
null |
String to append. true uses the formatter's default (e.g. 'm' for fmtMillions) |
labelCls |
string |
'xh-units-label' |
CSS class for label <span> |
tooltip |
boolean | (v) => string |
null |
true for auto-tooltip showing full-precision original value |
strictZero |
boolean |
true |
If false, values that round to zero at the given precision display as zero (using zeroDisplay if set) |
nullDisplay |
ReactNode |
'' |
Display value for null/undefined input |
zeroDisplay |
ReactNode |
null |
Display value for zero input |
asHtml |
boolean |
false |
Return HTML string instead of React element |
When precision is 'auto' (the default), fmtNumber selects precision based on value magnitude:
| Value Range | Precision |
|---|---|
| 0 | 2 |
| < 0.01 | 6 |
| < 100 | 4 |
| < 10,000 | 2 |
| >= 10,000 | 0 |
This provides sensible defaults for display, but many application column specs set an explicit precision based on business requirements and to ensure consistent alignment within a column.
Ledger format is standard in financial applications β negative values are wrapped in parentheses rather than prefixed with a minus sign. This is one of the most commonly used options in Hoist apps.
fmtNumber(-1234.56, {precision: 2, ledger: true}) // "(1,234.56)"
fmtNumber(1234.56, {precision: 2, ledger: true}) // "1,234.56 " (with alignment placeholder)The forceLedgerAlign option (default true) adds an invisible ) placeholder after positive
values so that digits in a column of mixed positive/negative numbers align vertically. Set it to
false when formatting standalone values outside of a columnar context.
Real-world example β a currency column with ledger formatting:
import {numberTextRenderer} from '@xh/hoist/format';
import {ExcelFormat} from '@xh/hoist/cmp/grid';
const ccyValueCol: ColumnSpec = {
align: 'right',
excelFormat: ExcelFormat.LEDGER_2DP,
textRenderer: numberTextRenderer({
precision: 2,
ledger: true,
forceLedgerAlign: false,
nullDisplay: '-'
}),
width: 120
};The colorSpec option applies CSS classes or inline styles based on the sign of the value.
Set to true for Hoist's default color classes, or provide a ColorSpec object with custom
classes or CSSProperties:
interface ColorSpec {
pos?: string | CSSProperties; // Applied to positive values
neg?: string | CSSProperties; // Applied to negative values
neutral?: string | CSSProperties; // Applied to zero values
}Default classes (when colorSpec: true): xh-pos-val, xh-neg-val, xh-neutral-val.
// Default color classes β green for positive, red for negative
numberRenderer({precision: 0, ledger: true, colorSpec: true})
// Custom: use intent classes for specific semantic meaning
fmtNumber(overdueAmount, {prefix: '$', colorSpec: {pos: 'xh-intent-danger'}})
// Custom: inline CSS styles instead of classes
fmtNumber(value, {colorSpec: {pos: {color: '#00aa00'}, neg: {color: '#cc0000'}}})Text renderers accept class names only. To share one spec between the two kinds, type it as
a ColorClassSpec, which holds a class name per sign:
const pnlColors: ColorClassSpec = {pos: 'app-gain', neg: 'app-loss'};
numberRenderer({precision: 0, colorSpec: pnlColors})
numberTextRenderer({precision: 0, colorSpec: pnlColors})ColorSpec is commonly combined with ledger, withPlusSign, or withSignGlyph for financial
P&L columns:
// P&L column
const pnlCol: ColumnSpec = {
field: {name: 'pnl', type: 'number'},
headerName: 'P&L',
align: 'right',
width: 130,
absSort: true,
tooltip: val => fmtNumberTooltip(val, {ledger: true}),
textRenderer: numberTextRenderer({
precision: 0,
ledger: true,
colorSpec: true
})
};Controls trailing zero behavior. Can be true, false, or a number specifying a minimum
number of decimal places to pad to (without extending all the way to full precision):
// precision: 4, zeroPad: true β "1.2000"
// precision: 4, zeroPad: 2 β "1.20" (but "1.234" stays "1.234")
// precision: 4, zeroPad: false β "1.2"When precision is a fixed number, zeroPad defaults to true. When precision is 'auto',
zeroPad defaults to false. A zeroPad of 0 is the same as false.
Digits come from the browser's Intl.NumberFormat, fixed to en-US. Values round half away from
zero on their decimal digits, for both signs: 2.5 gives 3, -2.5 gives -3, and 1.005 at 2
places gives 1.01. Near a tie, Hoist shifts the decimal point before it rounds, which absorbs most
float error from arithmetic. So fmtPercent(0.0045, {precision: 1}) gives "0.5%", although
0.0045 * 100 is 0.44999999999999996 in floating point.
Infinity renders as β. A string renders as JavaScript's Number() reads it, so '1234.5'
formats and '1,234.5' renders as NaN. Parse formatted text with parseNumber() first.
These wrap fmtNumber with pre-applied scaling and defaults for common financial use cases:
Divide value by the corresponding scale factor before formatting. When label: true, auto-appends
'k', 'm', or 'b' respectively.
fmtMillions(2500000, {precision: 1, label: true}) // "2.5m"
fmtThousands(45000, {precision: 0, label: true}) // "45k"
fmtBillions(1200000000, {precision: 2, label: true}) // "1.20b"Example of a market value column, in millions:
import {millionsTextRenderer, fmtNumberTooltip} from '@xh/hoist/format';
const mktValCol: ColumnSpec = {
field: {name: 'mktVal', type: 'number'},
headerName: 'Mkt Value (m)',
align: 'right',
width: 130,
absSort: true,
tooltip: val => fmtNumberTooltip(val, {ledger: true}),
textRenderer: millionsTextRenderer({precision: 3, ledger: true})
};Automatically scales to millions or billions based on the magnitude of the value. Applied defaults
include ledger: true and label: true.
fmtQuantity(500000) // "500,000"
fmtQuantity(2500000) // "2.50m"
fmtQuantity(1200000000) // "1.20b"Supports useMillions and useBillions options (both default true) to control which scale
thresholds are active.
Formats a market price with intelligent precision β 2 decimal places for values under 1000, 0 for larger values.
fmtPrice(42.5) // "42.50"
fmtPrice(1500) // "1,500"Multiplies value by 100 and appends %. This matches Excel's percentage formatting β pass the
raw decimal ratio, not a pre-multiplied value.
fmtPercent(0.456) // "45.60%"
fmtPercent(0.456, {precision: 0}) // "46%"
fmtPercent(-0.032, {
precision: 1,
colorSpec: true,
withSignGlyph: true
}) // "βΎ3.2%" (in red)Real-world example β a delta column with color and sign glyphs:
import {percentRenderer} from '@xh/hoist/format';
{
field: {name: 'deltaPeriod', type: 'number'},
renderer: percentRenderer({
precision: 0,
colorSpec: true,
withSignGlyph: true,
nullDisplay: '-'
})
}Renders a minimally formatted, full-precision number for use in tooltips. Supports only the
ledger option. Returns an HTML string (asHtml: true).
// Commonly used for grid column tooltips alongside a scaled or rounded formatter
tooltip: val => fmtNumberTooltip(val, {ledger: true}),
textRenderer: millionsTextRenderer({precision: 3, ledger: true})Parses shorthand number strings with k/m/b suffixes back to numeric values. Useful for inputs that accept shorthand entry:
parseNumber('1.5k') // 1500
parseNumber('2.5m') // 2500000
parseNumber('0.5b') // 500000000
parseNumber('1,234') // 1234Hoist defaults to the unambiguous YYYY-MM-DD date format (ISO 8601). XH recommends this format
for most applications β it sorts naturally, avoids confusion between month/day ordering conventions,
and is internationally understood. Avoid the US-centric MM/DD/YYYY format, which is
ambiguous and easily misread in international or multi-region contexts.
| Constant | Value | Example Output |
|---|---|---|
DATE_FMT |
'YYYY-MM-DD' |
2026-02-08 |
DATETIME_FMT |
'YYYY-MM-DD h:mma' |
2026-02-08 3:45pm |
DATETIMESEC_FMT |
'YYYY-MM-DD h:mm:ssa' |
2026-02-08 3:45:30pm |
TIME_FMT |
'h:mma' |
3:45pm |
MONTH_DAY_FMT |
'MMM D' |
Feb 8 |
| Function | Default Format | Description |
|---|---|---|
fmtDate(v, opts?) |
'YYYY-MM-DD' |
Standard date |
fmtDateTime(v, opts?) |
'YYYY-MM-DD h:mma' |
Date with time |
fmtDateTimeSec(v, opts?) |
'YYYY-MM-DD h:mm:ssa' |
Date with time and seconds |
fmtTime(v, opts?) |
'h:mma' |
Time only |
fmtCompactDate(v, opts?) |
(varies) | Adaptive format based on distance from today |
All accept Date, MomentJS, LocalDate, string, or numeric timestamp inputs.
| Option | Type | Default | Description |
|---|---|---|---|
fmt |
string |
(varies by function) | MomentJS format string |
nullDisplay |
ReactNode |
'' |
Display value for null input |
tooltip |
(v) => string |
null |
Tooltip generator function |
asHtml |
boolean |
false |
Return HTML string instead of React element |
Options can be passed as a string shorthand for fmt:
fmtDate(date, 'MM/DD/YYYY') // shorthand
fmtDate(date, {fmt: 'MM/DD/YYYY'}) // equivalentIntelligently selects a format based on how far the date is from today, showing more detail for recent dates and falling back to the full date for older ones. This is a good choice for columns or displays where space is limited and recency matters more than a consistent format.
The formatter classifies dates into three buckets:
| Distance | Default Format | Example (if today is 2026-02-08) |
|---|---|---|
| Same day | 'h:mma' for Date/Moment, 'MMM D' for LocalDate |
3:45pm |
Within distantThreshold months (default 6) |
'MMM D' |
Jan 15 |
Beyond distantThreshold months |
'YYYY-MM-DD' |
2025-03-22 |
CompactDateFormatOptions:
| Option | Type | Default | Description |
|---|---|---|---|
sameDayFmt |
string |
'h:mma' / 'MMM D' |
Format for today. Defaults differ for Date vs LocalDate |
nearFmt |
string |
'MMM D' |
Format for dates within the threshold |
distantFmt |
string |
'YYYY-MM-DD' |
Format for dates beyond the threshold |
distantThreshold |
number |
6 |
Number of months (before and after today) to consider "near" |
import {fmtCompactDate, compactDateTextRenderer} from '@xh/hoist/format';
// Assuming today is 2026-02-08:
fmtCompactDate(new Date('2026-02-08T15:45:00')) // "3:45pm" (same day β time only)
fmtCompactDate(new Date('2026-01-15T10:00:00')) // "Jan 15" (last month β month + day)
fmtCompactDate(new Date('2025-03-22T10:00:00')) // "2025-03-22" (11 months ago β full date)
// LocalDate same-day defaults to 'MMM D' since there is no time component
fmtCompactDate(LocalDate.today()) // "Feb 8"
// Use as a column formatter for activity/event timestamps
{field: 'lastActivity', textRenderer: compactDateTextRenderer()}
// Custom thresholds - e.g. show full date after only 2 months
{field: 'updatedDate', textRenderer: compactDateTextRenderer({distantThreshold: 2})}Creates a copy of a plain object with timestamp values replaced by formatted strings. Identifies
timestamp properties by key suffix matching (default: keys ending in 'time', 'date', or
'timestamp'). Used primarily by the Hoist Admin Console; useful for formatting debug data.
Returns a replacer function for JSON.stringify() that formats timestamps inline.
Wraps a value in a styled <span>:
fmtSpan('Active', {className: 'status-active', style: {fontWeight: 'bold'}})Options: className, style, title, leadSpc, trailSpc, asHtml.
Pretty-prints a JSON string or object with configurable indentation:
fmtJson({a: 1, b: 2}) // Formatted with 2-space indent (default)
fmtJson(jsonString, {space: 4}) // 4-space indentCapitalizes the first letter of each space-separated word.
The most common pattern across Hoist applications is defining shared column specs in a central
module, pairing formatters with matching ExcelFormat values for consistent display and export:
import {numberTextRenderer, dateTextRenderer} from '@xh/hoist/format';
import {ExcelFormat} from '@xh/hoist/cmp/grid';
// Shared column definitions
export const hoursCol: ColumnSpec = {
field: {name: 'hours', type: 'number'},
excelFormat: ExcelFormat.NUM_2DP,
textRenderer: numberTextRenderer({precision: 2, nullDisplay: '-'})
};
export const dueDateCol: ColumnSpec = {
field: {name: 'dueDate', type: 'localDate'},
headerName: 'Due',
textRenderer: dateTextRenderer()
};Applications often wrap fmtNumber in app-specific functions that add domain conventions
(currency prefixes, custom scaling thresholds, masking):
// App-specific money formatter with scaling
import {fmtNumber, NumberFormatOptions} from '@xh/hoist/format';
export function fmtMoney(v: number, opts: NumberFormatOptions = {}) {
if (v == null) v = 0;
return v >= 1000000
? fmtNumber(v / 1000, {precision: 0, prefix: '$', ...opts, label: 'k'})
: fmtNumber(v, {precision: 0, prefix: '$', ...opts});
}
// Use in components
span(fmtMoney(summary.openAmount))A grid column that switches scale by an app setting needs a wrapper text renderer that picks the
current scale on each call. The column reads cellClassRules once, when it is created, so give the
wrapper rules that defer to the current one. Refresh the column's cells when the setting changes, for
example with gridModel.agApi?.refreshCells({columns: ['pnl'], force: true}).
import {XH} from '@xh/hoist/core';
import {millionsTextRenderer, thousandsTextRenderer, type TextRenderer} from '@xh/hoist/format';
import {mapValues} from 'lodash';
const opts = {precision: 1, ledger: true, colorSpec: true, label: true} as const,
inMillions = millionsTextRenderer(opts),
inThousands = thousandsTextRenderer(opts),
current = () => (XH.getPref('pnlInMillions') ? inMillions : inThousands);
export const pnlTextRenderer: TextRenderer<number> = v => current()(v);
pnlTextRenderer.cellClassRules = mapValues(
inMillions.cellClassRules,
(_, cls) => params => current().cellClassRules[cls](params)
);Financial apps frequently display values with dynamic currency labels:
// Currency amount with dynamic code label
import {fmtNumber} from '@xh/hoist/format';
fmtNumber(amount, {
precision: 0,
label: currency.code, // e.g. 'USD', 'EUR'
ledger: true
})// Day-of-week column using custom MomentJS format string
const dayOfWeekCol: ColumnSpec = {
colId: 'trade_date_day',
field: {name: 'trade_date', type: 'localDate'},
displayName: 'Day of Week',
textRenderer: dateTextRenderer({fmt: 'dddd'})
};Hoist does not yet offer built-in localization, but it is on the roadmap. Today it assumes English
and US conventions: its own UI text (buttons, menus, prompts) is English, fmtDate() uses MomentJS's
default en locale, fmtNumber() uses Intl.NumberFormat fixed to en-US, and the calendars of
both desktop and mobile DateInput are fixed to date-fns' en-US locale. Each of these libraries -
along with ag-Grid, Highcharts, and Blueprint - supports other locales, so localizing a Hoist app is
achievable, but it means coordinating all of them and is not yet a turnkey setting.
/cmp/grid/- GridModel columns use formatters and renderers extensively/data/- Field types determine appropriate formatters/core/- HoistModel, hoistCmp for component integration