Math Expression Calculator Guide: JavaScript Math Reference & Scientific Computing

~12 min read

Whether you're a front-end developer working on data visualization, a back-end engineer implementing business algorithms, or a data analyst doing quick calculations, understanding math expression evaluation and JavaScript's Math functions is essential. This guide starts with the Math object basics and progresses to scientific computing techniques and expression parsing.

JavaScript Math Object Complete Reference

JavaScript's built-in Math object provides a rich set of mathematical constants and functions, available without any additional dependencies.

Mathematical Constants

ConstantValueDescription
Math.PI3.14159265...Pi (π)
Math.E2.71828182...Euler's number (e)
Math.LN20.69314718...Natural log of 2
Math.LN102.30258509...Natural log of 10
Math.LOG2E1.44269504...Log base 2 of e
Math.LOG10E0.43429448...Log base 10 of e
Math.SQRT21.41421356...Square root of 2
Math.SQRT1_20.70710678...1 / square root of 2

Basic Arithmetic Functions

MethodDescriptionExample
Math.abs(x)Absolute valueMath.abs(-5) → 5
Math.round(x)Round to nearestMath.round(4.6) → 5
Math.ceil(x)Round upMath.ceil(4.1) → 5
Math.floor(x)Round downMath.floor(4.9) → 4
Math.trunc(x)Truncate decimalMath.trunc(-4.7) → -4
Math.max(...)Maximum valueMath.max(1,5,3) → 5
Math.min(...)Minimum valueMath.min(1,5,3) → 1
Math.pow(x,y)PowerMath.pow(2,10) → 1024
Math.sqrt(x)Square rootMath.sqrt(16) → 4
Math.cbrt(x)Cube rootMath.cbrt(27) → 3
Math.hypot(...)Pythagorean theoremMath.hypot(3,4) → 5

Trigonometric Functions

MethodDescriptionExample
Math.sin(x)Sine (radians)Math.sin(Math.PI/2) → 1
Math.cos(x)CosineMath.cos(0) → 1
Math.tan(x)TangentMath.tan(Math.PI/4) → 1
Math.asin(x)Arc sineMath.asin(1) → π/2
Math.acos(x)Arc cosineMath.acos(1) → 0
Math.atan2(y,x)Four-quadrant arc tangentMath.atan2(1,1) → π/4

Logarithmic & Exponential Functions

Math.log(x)     // Natural logarithm ln(x)
Math.log2(x)    // Log base 2
Math.log10(x)   // Log base 10
Math.exp(x)     // e^x
Math.expm1(x)   // e^x - 1 (more precise for small x)

Floating-Point Precision Issues & Solutions

JavaScript uses IEEE 754 double-precision floating point, which causes some seemingly simple calculations to produce unexpected results:

0.1 + 0.2          // → 0.30000000000000004
0.1 + 0.2 === 0.3  // → false
9999999999999999    // → 10000000000000000

Solutions

1. Integer arithmetic—convert decimals to integers first:

function add(a, b) {
  const factor = 10 ** 10;
  return (Math.round(a * factor) + Math.round(b * factor)) / factor;
}
add(0.1, 0.2)  // → 0.3

2. toFixed rounding—suitable for display:

(0.1 + 0.2).toFixed(2)  // → "0.30"
Number((0.1 + 0.2).toFixed(2))  // → 0.3

3. High-precision libraries—for financial calculations:

// decimal.js
import Decimal from 'decimal.js';
new Decimal(0.1).plus(0.2).toString()  // → "0.3"

Scientific Computing Techniques

Permutations & Combinations

// Factorial
function factorial(n) {
  if (n <= 1) return 1;
  let result = 1;
  for (let i = 2; i <= n; i++) result *= i;
  return result;
}

// Permutations P(n, k) = n! / (n-k)!
function permutation(n, k) {
  return factorial(n) / factorial(n - k);
}

// Combinations C(n, k) = n! / (k! * (n-k)!)
function combination(n, k) {
  return factorial(n) / (factorial(k) * factorial(n - k));
}

// Large-number combinations (prevents overflow)
function comb(n, k) {
  if (k > n - k) k = n - k;
  let result = 1;
  for (let i = 0; i < k; i++) {
    result = result * (n - i) / (i + 1);
  }
  return result;
}
comb(100, 3)  // → 161700

Statistical Functions

const data = [23, 45, 12, 67, 34, 89, 56];

// Mean
const mean = arr => arr.reduce((s, v) => s + v, 0) / arr.length;

// Median
const median = arr => {
  const sorted = [...arr].sort((a, b) => a - b);
  const mid = Math.floor(sorted.length / 2);
  return sorted.length % 2 ? sorted[mid] : (sorted[mid-1] + sorted[mid]) / 2;
};

// Standard deviation
const stddev = arr => {
  const m = mean(arr);
  return Math.sqrt(arr.reduce((s, v) => s + (v - m) ** 2, 0) / arr.length);
};

mean(data)    // → 46.57
median(data)  // → 45
stddev(data)  // → 25.26

Angle & Radian Conversion

const deg2rad = deg => deg * Math.PI / 180;
const rad2deg = rad => rad * 180 / Math.PI;

deg2rad(180)  // → 3.14159...
rad2deg(Math.PI)  // → 180

Linear Interpolation & Mapping

// Linear interpolation
function lerp(a, b, t) {
  return a + (b - a) * t;
}

// Map a value to a new range
function map(value, inMin, inMax, outMin, outMax) {
  return outMin + (value - inMin) * (outMax - outMin) / (inMax - inMin);
}

lerp(0, 100, 0.5)     // → 50
map(50, 0, 100, 0, 1)  // → 0.5

Distance Calculations

// Euclidean distance
const euclidean = (a, b) => Math.hypot(a[0]-b[0], a[1]-b[1]);

// Manhattan distance
const manhattan = (a, b) => Math.abs(a[0]-b[0]) + Math.abs(a[1]-b[1]);

// Haversine formula (distance between two points on Earth, in km)
function haversine(lat1, lon1, lat2, lon2) {
  const R = 6371;
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a = Math.sin(dLat/2)**2 +
    Math.cos(lat1*Math.PI/180) * Math.cos(lat2*Math.PI/180) *
    Math.sin(dLon/2)**2;
  return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
}

Expression Evaluation & Parsing

Sometimes you need to parse and evaluate user-entered math expressions at runtime. Here are several common approaches:

Using the Function Constructor (Simple Cases)

function evaluate(expr) {
  return new Function('return ' + expr)();
}
evaluate('2 * (3 + 4)')  // → 14
evaluate('Math.sqrt(144)')  // → 12
Security warning: new Function executes arbitrary code—use only in trusted environments. For user input, use a dedicated expression parsing library like math.js, which provides sandboxed evaluation.

Using the math.js Library

import { evaluate } from 'mathjs';

// Basic arithmetic
evaluate('2 + 3 * 4')  // → 14

// Variables
evaluate('x * y', { x: 3, y: 4 })  // → 12

// Functions
evaluate('sqrt(16) + sin(pi/2)')  // → 5

// Matrix operations
evaluate('det([[1, 2], [3, 4]])')  // → -2

// Unit conversion
evaluate('2 inch to cm')  // → 5.08 cm

FAQ

Can JavaScript handle complex number arithmetic?

Native JavaScript has no complex number type, but you can simulate them with objects: {re: 1, im: 2} represents 1+2i, and manually implement addition, subtraction, multiplication, and division. For a more convenient approach, use the math.js library, which provides full complex number support, matrix operations, and symbolic computation.

How do I solve JavaScript floating-point precision issues?

Three main approaches: convert decimals to integer arithmetic (good for simple cases), use toFixed() for rounding (good for display), or import high-precision libraries like decimal.js or big.js (for financial, scientific, or other precision-critical calculations).

How can I evaluate math expressions in a web page?

Use the RiseTop online math expression calculator, which supports entering math expressions directly and computing results in real time—including variable assignment, common math functions, and complex nested expressions, with no software installation required.

Enter an expression, get an instant result

Open Math Expression Calculator →