Skip to content

fmt

Dedicated formatting function. Skips expression parsing — faster than calc for pure formatting.

Signature

typescript
function fmt(
  value: number | string,
  format?: string,
  options?: FmtOptions,
): string | number;

Basic Usage

javascript
import { fmt } from "a-calc";

fmt(100, "=2"); // '100.00'
fmt(1234567, ","); // '1,234,567'
fmt(0.1234, "%=2"); // '12.34%'
fmt(1234567, "!c"); // '1.23M'

Format String Reference

Decimal Places

javascript
fmt(3.14159, "=2"); // '3.14'
fmt(3.14159, "<=2"); // '3.14'
fmt(3.1, ">=3"); // '3.100'
fmt(3.14159, ">=2<=4"); // '3.1415'

Rounding

javascript
fmt(1.125, "~5=2"); // '1.13'  round half up
fmt(1.125, "~6=2"); // '1.12'  banker's rounding
fmt(1.124, "~+=2"); // '1.13'  ceil
fmt(1.129, "~-=2"); // '1.12'  truncate (default)

Thousands

javascript
fmt(1234567, ","); // '1,234,567'
fmt(1234567.89, ",=2"); // '1,234,567.89'
fmt(1234567, "!t:eu"); // '1.234.567'

Percentage

javascript
fmt(0.1234, "%"); // '12.34%'
fmt(0.1234, "%=1"); // '12.3%'

Scientific Notation

javascript
fmt(123456789, "!e"); // '1.23456789e+8'
fmt(123456789, "!e=2"); // '1.23e+8'

Sign

javascript
fmt(100, "+"); // '+100'
fmt(-100, "+"); // '-100'

Fraction

javascript
fmt(0.5, "/"); // '1/2'
fmt(0.75, "/"); // '3/4'

Return Number

javascript
fmt(100, "=2!n"); // 100 (number)
fmt(100, "=2"); // '100.00' (string)

Options

javascript
fmt("abc", "=2", { _error: "N/A" }); // 'N/A'

fmt(1500, "!c", {
  _compact_symbols: ["", "K", "M"],
  _compact_step: 1000,
}); // '1.5K'

vs calc

Featurecalcfmt
Expression evaluation
Variables
Formatting
Performanceslowerfaster
API stylecalc('100 | =2')fmt(100, '=2')

Real-World Usage

javascript
// Table data formatting
const data = [1234.5, 5678.9, 9012.3];
data.map((n) => fmt(n, ",=2"));
// ['1,234.50', '5,678.90', '9,012.30']

// Financial display
fmt(1234567.89, ",=2"); // '1,234,567.89'
fmt(0.0523, "%=2+"); // '+5.23%'
fmt(-0.0312, "%=2+"); // '-3.12%'

Released under the MIT License