Skip to content

Formatting

Use | to separate the expression from formatting rules.

Decimal Places

javascript
calc("10 / 3 | =2"); // '3.33'  exactly 2 places
calc("1.5 | =3"); // '1.500' pad with zeros
calc("10 / 3 | <=2"); // '3.33'  at most 2 places, no padding

Rounding Modes

Default is truncation. Other modes are available:

javascript
calc("1.129 | =2"); // '1.12'  truncate (default)
calc("1.125 | ~5=2"); // '1.13'  round half up
calc("1.125 | ~6=2"); // '1.12'  banker's rounding (common in finance)

Thousands Separator

javascript
calc("1234567 | ,"); // '1,234,567'
calc("1234567.89 | =2,"); // '1,234,567.89'

Percentage

javascript
calc("0.1234 | %"); // '12.34%'
calc("0.1234 | %=2"); // '12.34%'

Show Positive Sign

javascript
calc("100 | +"); // '+100'
calc("-100 | +"); // '-100'

Return Number Type

javascript
calc("1 + 2"); // '3' (string)
calc("1 + 2 | !n"); // 3 (number)

Combining Rules

javascript
calc("1234567.126 | ~5=2,+"); // '+1,234,567.13'
calc("0.12345 | ~5%=2"); // '12.35%'

Quick Reference

RuleDescriptionExample
=NExactly N decimal places=2 → 1.50
<=NAt most N decimal places<=2 → 1.5
~5Round half up1.125 → 1.13
~6Banker's rounding1.125 → 1.12
,Thousands separator1234567 → 1,234,567
%Percentage0.12 → 12%
+Show positive sign100 → +100
!nReturn number type'3' → 3

The fmt Function

Use fmt for pure formatting — it's more efficient:

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

fmt(1234567, ",=2"); // '1,234,567.00'
fmt(0.1234, "%=2"); // '12.34%'

Next Steps

Released under the MIT License