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

  1. Reads the value attribute from the <data> element and parses it as a number
  2. Stores the original text content as a title attribute (visible on hover)
  3. Formats the number using Intl.NumberFormat with the specified style
  4. 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:

1,234,567

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%):

85% 2.4%

Compact

Abbreviated notation for large numbers (e.g., 1.5M, 45.6K):

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:

ProductRevenue
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.

Accessibility

  • The original text is preserved as a title attribute, accessible on hover
  • The semantic <data> element with value attribute 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