math-literal

A TypeScript library for precise mathematical expressions using template literals with BigNumber support.
Overview
math-literal provides a clean, readable syntax for complex mathematical operations using JavaScript template literals while maintaining arbitrary precision arithmetic through the decimal.js library.
The Problem
Traditional BigNumber arithmetic can become unreadable with nested operations:
BigNumber.add(BigNumber.div(BigNumber.plus(a, BigNumber.times(b, c)), d), e)
The Solution
With math-literal, complex expressions become intuitive:
import { math } from 'math-literal';
const result = math`(${a} + ${b} * ${c}) / ${d} + ${e}`;
Installation
npm install math-literal
Or using Yarn:
yarn add math-literal
Or using Bun:
bun add math-literal
Quick Start
import { math, mathIs, BigNumber } from 'math-literal';
const sum = math`${10} + ${20}`;
const product = math`${5} * ${6}`;
const result = math`(${10} + ${5}) * ${2}`;
const isGreater = mathIs`${10} > ${5}`;
const isEqual = mathIs`${5} === ${5}`;
const bigNum = BigNumber.from('123.456');
const precise = math`${bigNum} * ${2}`;
console.log(BigNumber.toString(precise));
Features
- Template Literal Syntax: Write mathematical expressions naturally using template literals
- Arbitrary Precision: Built on
decimal.js for accurate decimal arithmetic
- Type Safety: Full TypeScript support with proper type definitions
- Comprehensive Operations: Support for arithmetic, comparison, and mathematical functions
- Clean API: Intuitive syntax that reads like mathematical notation
API Reference
Core Functions
math
Evaluates mathematical expressions and returns a BigNumber result.
const result = math`${a} + ${b}`;
mathIs
Evaluates comparison and logical expressions, returning a boolean.
const isTrue = mathIs`${a} > ${b} && ${c} < ${d}`;
Supported Operators
Arithmetic Operators
+ | Addition | math${a} + ${b}`` |
- | Subtraction | math${a} - ${b}`` |
*, x | Multiplication | math${a} * ${b}`` |
/ | Division | math${a} / ${b}`` |
**, ^ | Exponentiation | math${a} ** ${b}`` |
<< | Left shift decimals | math${a} << ${2}`` |
>> | Right shift decimals | math${a} >> ${2}`` |
Mathematical Functions
round() | Round to nearest integer | mathround(${a})`` |
floor() | Round down | mathfloor(${a})`` |
ceil() | Round up | mathceil(${a})`` |
sqrt() | Square root | mathsqrt(${a})`` |
abs() | Absolute value | mathabs(${a})`` |
ln() | Natural logarithm | mathln(${a})`` |
exp() | Exponential (e^x) | mathexp(${a})`` |
max() | Maximum of two values | mathmax(${a}, ${b})`` |
min() | Minimum of two values | mathmin(${a}, ${b})`` |
Comparison Operators (for mathIs)
> | Greater than | mathIs${a} > ${b}`` |
>= | Greater than or equal | mathIs${a} >= ${b}`` |
< | Less than | mathIs${a} < ${b}`` |
<= | Less than or equal | mathIs${a} <= ${b}`` |
===, == | Equal to | mathIs${a} === ${b}`` |
!==, != | Not equal to | mathIs${a} !== ${b}`` |
Logical Operators (for mathIs)
&& | Logical AND | mathIs${a} > 0 && ${b} < 10`` |
|| | Logical OR | mathIs${a} < 0 || ${b} > 10`` |
BigNumber Utilities
The library exports a comprehensive BigNumber namespace with utility functions:
import { BigNumber } from 'math-literal';
const num = BigNumber.from('123.456');
const fromNumber = BigNumber.from(789);
BigNumber.isBigNumber(num);
BigNumber.toString(num);
BigNumber.toNumber(num);
BigNumber.isEq(num, '123.456');
BigNumber.isGt(num, 100);
BigNumber.isLt(num, 200);
const sum = BigNumber.add(num, 10);
const diff = BigNumber.minus(num, 10);
const product = BigNumber.mul(num, 2);
const quotient = BigNumber.div(num, 2);
const rounded = BigNumber.round({}, num);
const fixed = BigNumber.toFixed({ precision: 2 }, num);
Advanced Examples
Complex Financial Calculations
import { math, BigNumber } from 'math-literal';
function compoundInterest(principal: number, rate: number, n: number, time: number) {
const r = BigNumber.from(rate);
const base = math`${1} + ${r} / ${n}`;
const exponent = n * time;
return math`${principal} * ${base} ** ${exponent}`;
}
const investment = compoundInterest(1000, 0.05, 12, 10);
console.log(BigNumber.toFixed({ precision: 2 }, investment));
Statistical Operations
function standardDeviation(values: number[]) {
const n = values.length;
const mean = values.reduce((sum, val) =>
BigNumber.add(sum, val), BigNumber.from(0)
);
const avgMean = math`${mean} / ${n}`;
const variance = values.reduce((sum, val) => {
const diff = math`${val} - ${avgMean}`;
return BigNumber.add(sum, math`${diff} ** ${2}`);
}, BigNumber.from(0));
return math`sqrt(${variance} / ${n})`;
}
Conditional Logic
import { mathIs } from 'math-literal';
function validateTransaction(amount: number, balance: number, limit: number) {
const isValid = mathIs`${amount} > ${0} && ${amount} <= ${balance} && ${amount} <= ${limit}`;
if (isValid) {
console.log('Transaction approved');
} else {
console.log('Transaction denied');
}
}
Order of Operations
The library follows standard mathematical precedence:
- Parentheses
()
- Functions (
sqrt, abs, etc.)
- Exponentiation (
**, ^)
- Multiplication (
*, x) and Division (/)
- Addition (
+) and Subtraction (-)
- Comparison operators (
>, <, >=, <=, ==, !=)
- Logical operators (
&&, ||)
TypeScript Support
The library is written in TypeScript and provides complete type definitions:
import { BigNumber, math, mathIs } from 'math-literal';
const result: BigNumber = math`${10} + ${20}`;
const comparison: boolean = mathIs`${10} > ${5}`;
type BigNumberSource = string | number | BigNumber;
Development
Prerequisites
- Node.js 22+ or Bun
- npm, yarn, or bun package manager
Setup
git clone https://github.com/zhigang1992/math-literal.git
cd math-literal
npm install
npm test
npm run build
npm run lint
Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature)
- Commit your changes (
git commit -m 'Add some amazing feature')
- Push to the branch (
git push origin feature/amazing-feature)
- Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- Built on top of decimal.js for arbitrary precision arithmetic
- Inspired by the need for readable mathematical expressions in JavaScript
Author
Kyle Fang
Links