Most "calculator" tutorials stop at eval() or at four buttons. A scientific calculator is more interesting: it needs operator precedence, functions that take arguments, a degrees/radians switch, nPr and nCr, and scientific notation like 3.5E8.

In this post I'll build a small parser that handles all of that in about 120 lines, with no libraries and no eval(). Every example below was run in Node before I wrote it down. The calculator I built it for is here: free online scientific calculator.

Why not just use eval()?

eval() runs anything you give it, not only maths. If you use it anyway, you must check the input against a strict allow-list first. A parser avoids the problem: it can only ever produce a number, and you get clear errors for free (sin(30 is a missing bracket, not a mystery).

The plan

  1. Tokenize the string into numbers, names (sin, pi) and symbols (+, (, ,).
  2. Parse with recursive descent, one function per precedence level.
  3. Evaluate while parsing, so we never build a syntax tree.

Step 1: Tokenizing, including scientific notation

The one regular expression that matters is the number pattern. It accepts an optional exponent, so 3.5E8 and 4.2E-4 are each a single number token:

const re = /\s*(?:(\d+\.?\d*(?:E[+-]?\d+)?|\.\d+(?:E[+-]?\d+)?)|([A-Za-z]+)|(.))/gy; 

Group 1 is a number, group 2 is a name, group 3 is any other symbol. Numbers are tried first, so the E in 3.5E8 is never mistaken for Euler's number, which is just the name e on its own.

Step 2: Precedence with recursive descent

Each precedence level calls the next, tighter-binding one:

expr = term (("+" | "-") term)* term = unary (("*" | "/") unary)* unary = "-" unary | power power = primary ("^" unary)? primary = number | constant | name "(" args ")" | "(" expr ")" 

Two details are easy to get wrong:

  • -2^2 must be -4, not 4, so unary minus sits above the power rule.
  • 2^-3 must work, so the right-hand side of ^ goes back through unary.

Step 3: Degrees, radians and the maths functions

Trig functions take an angle, so the calculator needs a mode. I pass it in once and wrap the built-ins:

const toRad = (x) => (angleMode === "deg" ? (x * Math.PI) / 180 : x); const fromRad = (x) => (angleMode === "deg" ? (x * 180) / Math.PI : x); const funcs = { sin: (x) => Math.sin(toRad(x)), cos: (x) => Math.cos(toRad(x)), tan: (x) => Math.tan(toRad(x)), asin: (x) => fromRad(Math.asin(x)), acos: (x) => fromRad(Math.acos(x)), atan: (x) => fromRad(Math.atan(x)), log: Math.log10, ln: Math.log, sqrt: Math.sqrt, cbrt: Math.cbrt, abs: Math.abs, fact: factorial, nPr, nCr, mod: (a, b) => a % b, }; 

Step 4: Permutations and combinations without overflow

nPr(n, r) is n! / (n - r)! and nCr(n, r) is n! / (r! * (n - r)!). Computing full factorials overflows quickly, so multiply only the terms you need:

const nPr = (n, r) => { if (!Number.isInteger(n) || !Number.isInteger(r) || r < 0 || r > n) throw new Error("bad nPr"); let p = 1; for (let i = n - r + 1; i <= n; i++) p *= i; return p; }; const nCr = (n, r) => { if (!Number.isInteger(n) || !Number.isInteger(r) || r < 0 || r > n) throw new Error("bad nCr"); r = Math.min(r, n - r); // C(n, r) === C(n, n - r) let c = 1; for (let i = 1; i <= r; i++) c = (c * (n - r + i)) / i; return Math.round(c); }; 

The complete parser

function createCalculator({ angleMode = "deg" } = {}) { const toRad = (x) => (angleMode === "deg" ? (x * Math.PI) / 180 : x); const fromRad = (x) => (angleMode === "deg" ? (x * 180) / Math.PI : x); const factorial = (n) => { if (!Number.isInteger(n) || n < 0 || n > 170) throw new Error("fact needs 0-170"); let f = 1; for (let i = 2; i <= n; i++) f *= i; return f; }; const nPr = (n, r) => { if (!Number.isInteger(n) || !Number.isInteger(r) || r < 0 || r > n) throw new Error("bad nPr"); let p = 1; for (let i = n - r + 1; i <= n; i++) p *= i; return p; }; const nCr = (n, r) => { if (!Number.isInteger(n) || !Number.isInteger(r) || r < 0 || r > n) throw new Error("bad nCr"); r = Math.min(r, n - r); let c = 1; for (let i = 1; i <= r; i++) c = (c * (n - r + i)) / i; return Math.round(c); }; const funcs = { sin: (x) => Math.sin(toRad(x)), cos: (x) => Math.cos(toRad(x)), tan: (x) => Math.tan(toRad(x)), asin: (x) => fromRad(Math.asin(x)), acos: (x) => fromRad(Math.acos(x)), atan: (x) => fromRad(Math.atan(x)), log: Math.log10, ln: Math.log, sqrt: Math.sqrt, cbrt: Math.cbrt, abs: Math.abs, fact: factorial, nPr, nCr, mod: (a, b) => a % b, }; const consts = { pi: Math.PI, e: Math.E }; function tokenize(src) { const re = /\s*(?:(\d+\.?\d*(?:E[+-]?\d+)?|\.\d+(?:E[+-]?\d+)?)|([A-Za-z]+)|(.))/gy; const out = []; let m; while ((m = re.exec(src)) && m[0].trim() !== "") { if (m[1] !== undefined) out.push({ t: "num", v: parseFloat(m[1]) }); else if (m[2] !== undefined) out.push({ t: "id", v: m[2] }); else out.push({ t: "op", v: m[3] }); } return out; } function evaluate(src) { const tokens = tokenize(src); let i = 0; const peek = () => tokens[i]; const take = (v) => { const tok = tokens[i]; if (!tok || (v && tok.v !== v)) throw new Error(`Expected ${v || "token"}`); i++; return tok; }; function expr() { let x = term(); while (peek() && (peek().v === "+" || peek().v === "-")) { x = take().v === "+" ? x + term() : x - term(); } return x; } function term() { let x = unary(); while (peek() && (peek().v === "*" || peek().v === "/")) { x = take().v === "*" ? x * unary() : x / unary(); } return x; } function unary() { if (peek() && peek().v === "-") { take(); return -unary(); } return power(); } function power() { const base = primary(); if (peek() && peek().v === "^") { take(); return Math.pow(base, unary()); } return base; } function primary() { const tok = take(); if (tok.t === "num") return tok.v; if (tok.t === "op" && tok.v === "(") { const x = expr(); take(")"); return x; } if (tok.t === "id") { if (tok.v in consts) return consts[tok.v]; if (tok.v in funcs) { take("("); const args = [expr()]; while (peek() && peek().v === ",") { take(","); args.push(expr()); } take(")"); return funcs[tok.v](...args); } } throw new Error("Unexpected " + tok.v); } const result = expr(); if (i !== tokens.length) throw new Error("Unexpected " + tokens[i].v); if (!Number.isFinite(result)) throw new Error("Math error"); return Number(result.toPrecision(12)); // hides 0.49999999999999994-style noise } return { evaluate }; } 

Try it

const deg = createCalculator(); // degrees by default const rad = createCalculator({ angleMode: "rad" }); deg.evaluate("sin(30)"); // 0.5 deg.evaluate("asin(0.5)"); // 30 rad.evaluate("sin(pi/2)"); // 1 deg.evaluate("3.5E8"); // 350000000 deg.evaluate("4.2E-4"); // 0.00042 deg.evaluate("6.02E23*2"); // 1.204e+24 deg.evaluate("nPr(5,3)"); // 60 deg.evaluate("nCr(5,3)"); // 10 deg.evaluate("nCr(52,5)"); // 2598960 (five-card poker hands) deg.evaluate("-2^2"); // -4 deg.evaluate("2^-3"); // 0.125 deg.evaluate("2+3*4"); // 14 deg.evaluate("(2+3)*4"); // 20 deg.evaluate("1/0"); // throws "Math error" deg.evaluate("sin(30"); // throws "Expected )" 

The floating-point trap

Math.sin(Math.PI / 6) is 0.49999999999999994, not 0.5, because PI can't be stored exactly. Rounding the final result to 12 significant digits with toPrecision(12) makes sin(30) show 0.5, which is what a user expects. The trade-off is that you lose digits beyond about 12, so say so if you build a calculator for people who care about precision.

Where to take it next