Skip to content

Format Groups

Define reusable format strings to avoid repetition.

Basic Usage

javascript
import { calc, set_config } from "a-calc";

set_config({
  _fmt_groups: {
    money: "~6=2,", // banker's rounding + 2dp + thousands
    percent: "~5%=2", // percentage with 2dp
    compact: "!c !ua:shares", // compact with unit
  },
});

calc("12345.678 | #money"); // '12,345.68'
calc("0.1234 | #percent"); // '12.34%'
calc("1234567 | #compact"); // '1.23M shares'

Two Syntaxes

javascript
calc("12345.678 | #money"); // shorthand (recommended)
calc("12345.678 | !g:money"); // unified syntax

Variable Reference

javascript
set_config({
  _fmt_groups: { money: "~6=2,", percent: "~5%=2" },
});

const data = [
  { value: 12345.678, type: "money" },
  { value: 0.1234, type: "percent" },
];

data.forEach((item) => {
  console.log(calc("value | #@type", item));
});
// '12,345.68'
// '12.34%'

Common Group Examples

Finance

javascript
set_config({
  _fmt_groups: {
    money: "~6=2,",
    money_usd: "~6=2, !ub:$",
    rate: "~5%=4+",
    change: "~5%=2+",
  },
});

E-commerce

javascript
set_config({
  _fmt_groups: {
    price: "~6=2, !ua:$",
    discount: "~5%=0",
    qty: "=0,",
    rating: "=1",
  },
});

Combining with Other Formatting

Groups can be combined with additional format tokens:

javascript
calc("12345.678 | #money =4"); // '12,345.6780' (override precision)
calc("12345.678 | #money +"); // '+12,345.68' (add sign)
calc("12345.678 | #money !ua:$"); // '12,345.68$' (add unit)

Performance

Format groups use lazy compilation + automatic caching:

  • First call: compile and cache
  • Subsequent calls: use cache (fast)

Notes

  1. Only one group per expression is supported
  2. Missing group names produce a warning and return the original value
  3. Group names support letters, numbers, and underscores

Released under the MIT License