calc
The core function for precision arithmetic and formatting.
Signature
typescript
function calc(expr: string | number, options?: object | array): string | number;Parameters
expr
The expression to evaluate. Supports:
javascript
calc("123"); // number literal
calc("1 + 2 * 3"); // expression
calc("10 / 3 | =2"); // with formatting
calc("a + b", { a: 1, b: 2 }); // with variablesoptions
Variables and/or configuration:
| Property | Type | Default | Description |
|---|---|---|---|
_error | any | throws | Return value on error (instead of throwing) |
_unit | boolean | false | Enable unit arithmetic |
_compact_symbols | string[] | ["","K","M","B","T"] | Compact format symbols |
_compact_step | number|number[] | 1000 | Compact format step |
_empty_values | any[] | - | Values treated as empty in fallback |
_empty_check | function | - | Custom empty value checker |
[key: string] | any | - | Variable values |
Global-only options
These must be set via set_config, not in calc options:
_fmt,_unit_convert_out,_unit_convert_in,_unit_default_out,_unit_default_in_unit_position_map,_unit_thousands_map,_unit_compact_map_thousands,_compact
Return Value
Returns string by default. Returns number with !n format. Returns _error value on error.
Examples
Basic Calculation
javascript
import { calc } from "a-calc";
calc("1 + 2"); // '3'
calc("10 / 3"); // '3.33333...'
calc("2 ** 10"); // '1024'Variables
javascript
calc("a + b", { a: 1, b: 2 }); // '3'
// Array of data sources
calc("a + b", [{ a: 1 }, { b: 2 }]); // '3'Formatting
javascript
calc("10 / 3 | =2"); // '3.33'
calc("1234567 | ,"); // '1,234,567'
calc("0.1234 | %=2"); // '12.34%'Error Handling
javascript
calc("a + b"); // throws Error
calc("a + b", { _error: "-" }); // '-'
calc("a + b", { _error: 0 }); // 0Unit Arithmetic
javascript
calc("100$ + 50$", { _unit: true }); // '150$'Compact Format
javascript
calc("1234567 | !c"); // '1.23M'
calc("12345 | !c:wan"); // '1.23万'calc_space
Space-separated syntax variant:
javascript
import { calc_space } from "a-calc";
calc_space("1 + 2 | = 2"); // '3.00'
calc_space("100 | , = 2"); // '100.00'