Getting Started
Installation
bash
npm install a-calcbash
yarn add a-calcbash
pnpm add a-calcImport
javascript
import { calc } from "a-calc";javascript
const { calc } = require("a-calc");html
<script src="https://unpkg.com/a-calc/browser/index.js"></script>
<script>
const { calc } = a_calc;
</script>Precision Arithmetic
a-calc solves JavaScript's floating-point precision problem:
javascript
// Native JavaScript
0.1 + 0.2; // 0.30000000000000004
// With a-calc
calc("0.1 + 0.2"); // '0.3'All common operators are supported:
javascript
calc("1 + 2"); // '3' addition
calc("5 - 3"); // '2' subtraction
calc("2 * 3"); // '6' multiplication
calc("10 / 4"); // '2.5' division
calc("(1 + 2) * 3"); // '9' parenthesesUsing Variables
Pass a variable object as the second argument:
javascript
calc("price * quantity", { price: 9.9, quantity: 3 }); // '29.7'
// Nested properties are supported
calc("user.balance + bonus", {
user: { balance: 100 },
bonus: 50,
}); // '150'The second argument can also be an array to pull variables from multiple objects:
javascript
// Multiple data sources
calc("a + b", [{ a: 1 }, { b: 2 }]); // '3'
// Real-world: merge product data and config
calc("price * discount", [
{ price: 100 }, // product data
{ discount: 0.8 }, // promotion config
]); // '80'Formatting Output
Use | to add formatting:
javascript
calc("10 / 3 | =2"); // '3.33' 2 decimal places
calc("1234567 | ,"); // '1,234,567' thousands separator
calc("0.1234 | %"); // '12.34%' percentageError Handling
Missing variables throw by default. Use _error to return a fallback value:
javascript
calc("a + b", { _error: "0" }); // '0'
calc("a + b", { _error: "-" }); // '-'Next Steps
- Formatting — decimals, thousands, percentages in depth
- Chain API — fluent multi-step calculations
- Examples — finance, e-commerce, and more