Number Formatter

v0.0.10

v0.0.10StableHeadlessStatelessAccessibleApache-2.0
Installation mix mishka.ui.gen.headless number_formatter
Source View Source

Overview of the Phoenix and LiveView Headless Number Formatter Component

The Mishka Chelekom Headless Number Formatter writes a number as text with thousands separators, a decimal separator, fixed decimals and an optional prefix or suffix. It formats while the Phoenix LiveView template renders, so it needs no JavaScript and no hook. The output is one span with the class chelekom-number-formatter and your own class.

Separators come from the attributes you pass, and digits are always grouped in threes.

Base UI Number Formatter example - currency and grouped counts (Phoenix headless)

Base UI Number Formatter example - currency and grouped counts (Phoenix headless)

Revenue: $1,234,567.89

Downloads: 9 876 543

heex
<div class="space-y-1 text-sm text-neutral-700 dark:text-neutral-300">
  <p>
    Revenue:
    <.number_formatter
      value={1_234_567.89}
      prefix="$"
      decimal_scale={2}
      class="font-semibold tabular-nums text-neutral-900 dark:text-white"
    />
  </p>
  <p>
    Downloads:
    <.number_formatter
      value={9_876_543}
      thousand_separator=" "
      decimal_scale={0}
      class="font-semibold tabular-nums text-neutral-900 dark:text-white"
    />
  </p>
</div>

Number Formatter example - suffix and custom separators (Phoenix headless)

Number Formatter example - suffix and custom separators (Phoenix headless)

Conversion rate: 42.5%

Price: €1.234.567,89

heex
<div class="space-y-1 text-sm text-neutral-700 dark:text-neutral-300">
  <p>
    Conversion rate:
    <.number_formatter
      value={42.5}
      suffix="%"
      decimal_scale={1}
      class="font-semibold tabular-nums text-neutral-900 dark:text-white"
    />
  </p>
  <p>
    Price:
    <.number_formatter
      value={1_234_567.891}
      prefix="€"
      thousand_separator="."
      decimal_separator=","
      decimal_scale={2}
      class="font-semibold tabular-nums text-neutral-900 dark:text-white"
    />
  </p>
</div>

How a value is formatted

value takes a number or a numeric string. A string that is not numeric prints as 0. decimal_scale fixes the number of decimal places and rounds to them. Without it, an integer prints as it is and a float prints the way Elixir writes it.

thousand_separator defaults to a comma. Pass false in a template to turn grouping off. decimal_separator defaults to a period. prefix and suffix are added around the result, and the prefix comes before a minus sign, so -1234.5 with a "$" prefix prints as $-1,234.50.

Attributes and parts

The component has one part, the root span. It takes value, thousand_separator, decimal_separator, decimal_scale, prefix, suffix and class, and passes other global attributes to the span. The output is plain text, so assistive technology reads it as it reads any other text on the page.