Skip to content

Comparison Operators

Supported Operators

OperatorMeaningExample
>Greater than5 > 3true
<Less than5 < 3false
>=Greater than or equal5 >= 5true
<=Less than or equal5 <= 4false
==Equal5 == 5true
!=Not equal5 != 3true

Basic Usage

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

calc("5 > 3"); // true
calc("5 < 3"); // false
calc("5 >= 5"); // true
calc("5 <= 4"); // false
calc("5 == 5"); // true
calc("5 != 3"); // true

calc("x > y", { x: 10, y: 5 }); // true

Precise Comparison

a-calc uses high-precision Decimal arithmetic for comparisons:

javascript
// Native JavaScript
0.1 + 0.2 === 0.3; // false

// a-calc
calc("0.1 + 0.2 == 0.3"); // true
calc("0.1 * 3 == 0.3"); // true

Chained Comparisons

a-calc supports Python-style chained comparisons:

javascript
calc("1 < 5 < 10"); // true  (1 < 5 AND 5 < 10)
calc("1 < 5 > 10"); // false (1 < 5 but 5 is NOT > 10)

calc("min < x < max", { min: 0, x: 5, max: 10 }); // true
calc("a < b < c < d", { a: 1, b: 2, c: 3, d: 4 }); // true

Operator Precedence

OperatorsPrecedence
**8
* / % //7
+ -6
> < >= <=5
== !=4
&&3
||2
? :1

Real-World Examples

Price Range Check

javascript
// Using chained comparison
calc("minBudget <= price <= maxBudget", {
  price: 500,
  minBudget: 100,
  maxBudget: 1000,
}); // true

Tiered Discount

javascript
const getDiscount = (amount) =>
  calc(
    `
  amount >= 1000 ? 0.7 :
  (amount >= 500 ? 0.8 :
  (amount >= 200 ? 0.9 : 1))
`,
    { amount },
  );

getDiscount(1500); // '0.7'
getDiscount(300); // '0.9'

Released under the MIT License