Math Expression Evaluator
Safely evaluate math expressions with variables, parentheses and functions.
Supports + − × ÷ ^ % parentheses, unary minus, variables (x = …), and built-in functions: sqrt, abs, sin, cos, tan, asin, acos, atan, atan2, exp, ln, log, log2, log10, round, floor, ceil, trunc, min, max, pow, hypot, sign, fact, rad, deg. Constants: pi, e, tau.
x = 55y = x * 2 + 313hypotenuse = sqrt(x^2 + y^2)13.9283882772sin(pi / 6)0.5
How to use Math Expression Evaluator
What is a math expression evaluator?
A math expression evaluator takes a string like
sqrt(2) * pi + log(e) and returns a number. Under the hood it
parses the string into a syntax tree, then walks the tree to
compute the result — the same two-step process a programming-language
interpreter uses, just restricted to arithmetic. It is the moral
equivalent of typing the expression into a calculator, except the
input is a text field and the output is a number you can copy.
How it works
This evaluator is a small recursive-descent parser, the textbook approach for arithmetic grammars. The pipeline:
- Tokenise — scan the input into numbers, identifiers,
operators and punctuation.
12.5 + sin(x)becomes[NUM 12.5] [+] [IDENT sin] [(] [IDENT x] [)]. - Parse — apply operator-precedence climbing to build an
abstract syntax tree.
2 + 3 * 4becomesAdd(2, Mul(3, 4)), notMul(Add(2, 3), 4). - Evaluate — walk the tree, dispatching identifiers through a
fixed lookup table for functions (
sin,sqrt, …) and constants (pi,e,tau), and resolving variables from an environment that the user can populate withx = 5; …. - Return the final
Number.
The critical property: at no point does the evaluator call JavaScript
eval() or Function(). Each operator and function name is matched
against a closed allow-list of safe implementations. Anything outside
the list is a syntax error, not arbitrary code execution.
Why “safe” matters
The shortest possible expression evaluator in JavaScript is
x => eval(x) — one line, supports every JS operator, instantly
broken from a security perspective. eval will happily run
fetch('/api/admin/delete-everything') or read cookies or rewrite the
DOM. In a web page that accepts arbitrary user input — for example, a
shared calculator embedded in a multi-user app — eval-based
evaluation is an XSS vulnerability with extra steps.
A purpose-built parser is a few hundred lines and gives you exactly
the surface area you wanted: arithmetic, named functions you chose,
nothing else. It is the same reason JSON.parse exists rather than
“just eval the JSON”.
Common use cases
- Quick calculations that need named functions:
hypot(3, 4),log2(1024),fact(10),atan2(1, 1) * 4to recover π. - Formula testing before pasting into application code:
“does my conversion
c * 9/5 + 32actually give 98.6 at 37?” - Teaching arithmetic and precedence — paste expressions live and show the result; the parenthesisation rules become obvious quickly.
- Reproducible expressions in documentation. Write
(pi * d^2) / 4in a tutorial; readers can paste it and verify. - Lightweight scratchpad for engineers who would otherwise open a Python REPL just to compute one number.
How to use this math evaluator
- Type an expression into the input box. Whitespace is optional;
parentheses bind subexpressions; function calls use familiar
name(args)syntax with comma-separated arguments. - The result updates live as you type. Syntax errors are flagged with a short message and the position of the problem.
- To use variables, separate assignments with semicolons:
r = 3; area = pi * r ^ 2; area. The last expression’s value is the result; earlier assignments populate the environment. - To compute in degrees instead of radians, wrap with
rad():sin(rad(30))returns0.5. The trig functions themselves always take radians, matching every standard math library. - Copy the result, or copy the full expression to share it.
Supported operators and functions
- Operators:
+,-(binary and unary),*,/,%,^. - Grouping:
()to override precedence. - Constants:
pi,e,tau. - Power / roots / logs:
pow,sqrt,exp,log,ln,log10,log2. - Rounding:
round,floor,ceil,trunc,abs,sign. - Aggregates:
min,max,hypot(Euclidean norm of N args). - Trig (radians):
sin,cos,tan,asin,acos,atan,atan2(y, x). - Conversions:
rad(deg),deg(rad). - Combinatorics:
fact(n)for integer factorial up to ~170 before overflow.
Security considerations
The parser is the security boundary. Every identifier the user types
is checked against a fixed table; unknown identifiers raise a parse
error. Function arguments are evaluated, type-checked where it
matters, and passed to the corresponding JavaScript Math method.
There is no string concatenation into eval, no new Function, and
no access to the DOM, window, document, or any other host object
from inside the expression. The whole evaluator is pure: same input,
same output, no side effects.
Privacy
Every keystroke is parsed and evaluated locally in your browser tab. The page makes zero network requests after the initial load — you can verify in the Network panel. No expressions, variables or results are sent anywhere, logged, or used for analytics. Closing the tab discards all state.
Compatibility notes
The evaluator is plain JavaScript that targets every browser released
in the last decade. Numbers are IEEE-754 double-precision, identical
to JavaScript, Python float, Java double and every modern
spreadsheet. The grammar matches mathematical convention: precedence
follows PEMDAS, exponentiation is right-associative, function calls
use parenthesised arguments. There is no i, no complex numbers, no
symbolic algebra, and no plotting — for plotting use a graphing tool;
for symbolic computation use a CAS like SymPy or Mathematica.
Frequently asked questions
What operator precedence does the evaluator use?
^, right-associative) → multiplication, division, modulo (*, /, %, left-associative) → addition and subtraction (+, -, left-associative). So 2 + 3 * 4 is 14, not 20; 2 ^ 3 ^ 2 is 512 (right-associative, 2^(3^2)); and -3 ^ 2 is -9 (unary minus binds tighter than ^ would suggest in some languages — write (-3)^2 if you want 9). When in doubt, parenthesise.What functions and constants are supported?
+, -, *, /, % (modulo), ^ (power). Functions: sqrt, pow(x,y), exp, log (natural), ln (alias for natural log), log10, log2, abs, sign, round, floor, ceil, trunc, min(a,b,…), max(a,b,…), hypot(a,b,…), fact(n) for factorial. Trig in radians: sin, cos, tan, asin, acos, atan, atan2(y,x). Conversion helpers: rad(deg), deg(rad). Constants: pi, e, tau (= 2π). Variables: assign with = and chain with ;, for example x = 5; y = x * 2; y + 1 evaluates to 11.How is this different from a spreadsheet formula?
=A1*B1 references other cells, and the value updates when those cells change. This evaluator is a single expression evaluator — there are no cells, no fills, no IF/VLOOKUP/INDEX-MATCH. It excels at one-off calculations where you'd otherwise reach for the calculator app or a Python REPL: "what's sqrt(2) * pi?", "convert 37°C to °F using c * 9/5 + 32", "check that log2(1024) is exactly 10". For data tables, use a spreadsheet; for formula testing and quick arithmetic with named variables, use this.How precise are the results?
float, every spreadsheet, and most calculators. That means 0.1 + 0.2 evaluates to 0.30000000000000004, exactly as in any other JS environment — the issue is the float representation, not the parser. For exact decimal arithmetic (financial calculations, for example) use a decimal library in your application code; this evaluator is not the right tool when the last cent matters.Does the evaluator run my expressions on a server?
Number-typed result all run in your browser tab. There is no eval() involved (which is the whole point of a safe evaluator) and no network request — paste an expression with your Wi-Fi off and watch it work. No analytics are collected on the expressions you enter.Related tools
Percentage Calculator
Solve percentage problems in several modes.
Unit Converter
Convert between length, weight, volume, and more.
Aspect Ratio Calculator
Calculate aspect ratios for images and video.
Quadratic Equation Solver
Solve quadratic equations, including complex roots.
Circle Calculator
Calculate circle area, circumference, and more.
Triangle Calculator
Solve triangles from sides and angles.