data-format-number
Locale-aware number formatting using Intl.NumberFormat. Add data-format-number to any <data> element for automatic formatting.
Overview
The data-format-number attribute enhances native <data> elements by replacing their text content with a locale-aware formatted number. The value attribute carries the raw number, while the displayed text is formatted for the user's locale.
How It Works
- Reads the
valueattribute from the<data>element and parses it as a number - Stores the original text content as a
titleattribute (visible on hover) - Formats the number using
Intl.NumberFormatwith the specified style - Replaces the text content with the formatted string
The formatting uses the user's browser locale by default, so numbers display with the correct separators automatically.
Attributes
| Attribute | Type | Description |
|---|---|---|
data-format-number |
string | Format style: "" (decimal), "currency", "percent", "compact". |
value |
string | The raw numeric value. Standard HTML value attribute on <data>. |
data-currency |
string | ISO 4217 currency code (e.g., "USD", "EUR"). Required when style is "currency". |
data-locale |
string | Optional locale override (e.g., "de-DE"). Defaults to browser locale. |
data-format-number-init |
boolean | Set automatically to prevent double-binding. Do not set manually. |
Format Styles
Decimal (default)
Standard number formatting with locale-aware grouping separators:
Currency
Formats with currency symbol and locale-appropriate placement. Requires data-currency:
USD: $48,200
EUR: 48.200,00 EUR
GBP: 48,200 GBP
Percent
Multiplies by 100 and adds percent sign. Pass the decimal value (e.g., 0.85 for 85%):
Compact
Abbreviated notation for large numbers (e.g., 1.5M, 45.6K):
Locale Override
Use data-locale to force a specific locale for formatting:
German: 1.234.567,89
Japanese: 1,234,567.89
Common Use Cases
Revenue Table
Format currency values in a data table. The font-variant-numeric: tabular-nums CSS ensures columns align:
| Product | Revenue |
|---|---|
| Widget A | $142,500 |
| Widget B | $89,300 |
Dynamic Elements
Elements added to the DOM after page load are automatically enhanced via a MutationObserver. No manual initialization is needed.
Progressive Enhancement
The <data> element's original text serves as a fallback when JavaScript is unavailable. Write a reasonable pre-formatted value as the text content:
Accessibility
- The original text is preserved as a
titleattribute, accessible on hover - The semantic
<data>element withvalueattribute provides machine-readable data - Falls back to the original text content when JavaScript is unavailable
- No wrapper element — the
<data>is the enhanced element, keeping the accessibility tree clean