JavaScript library for exact rational arithmetic using BigInt
No floating-point errors. Every calculation maintains perfect precision using BigInt internally.
// JavaScript floats
0.1 + 0.2 === 0.3 // false!
// RatMath
R`0.1 + 0.2`.equals(R`0.3`) // true!
Built-in support for interval calculations, perfect for uncertainty analysis.
// Create intervals
const a = R`1:2` // [1, 2]
const b = R`0.5:1.5` // [0.5, 1.5]
// Operations preserve bounds
R`1:2 + 0.5:1.5` // [1.5, 3.5]
Smart type promotion: Integer โ Rational โ RationalInterval as needed.
R`5 + 7` // Integer(12)
R`5 / 2` // Rational(5/2)
R`5 + 1:2` // RationalInterval([6, 7])
Support for mixed numbers, repeating decimals, continued fractions, and more.
R`2..1/3` // Mixed: 2 and 1/3
R`0.#3` // Repeating: 0.333... = 1/3
R`3.~7~15~1` // Continued fraction = 355/113
Try the RatMath API directly in your browser. Press Ctrl+Enter (or Cmd+Enter) to run code:
R\`1/2\` // Rational
R\`42\` // Integer
R\`1:2\` // Interval
F\`3/4\` // Fraction (no reduction)
.add(other)
.subtract(other)
.multiply(other)
.divide(other)
.pow(n)
.equals(other)
.lessThan(other)
.greaterThan(other)
.lessThanOrEqual(other)
.greaterThanOrEqual(other)
.toString()
.toDecimal(limit)
.toMixed()
.toContinuedFraction()
.toScientific(precision)
import { R, Parser } from 'ratmath';
// Using template literals with expressions
const sum = R\`1/3 + 2/3\`; // Rational(1)
// Or using method calls
const third = R\`1/3\`;
const twoThirds = R\`2/3\`;
const sum2 = third.add(twoThirds); // Rational(1)
// Using Parser directly
const expr = Parser.parse("1/2 + 1/3"); // Rational(5/6)
// Working with intervals
const measurement = R\`5.2[+-0.05]\`; // [5.15, 5.25]