JS Precision Math: Choosing big.js vs mathjs

This post compares big.js and mathjs for JavaScript precision calculations, including pros, size, and usage considerations.

Apr 1, 2020 · 2 min read · 229 Words · -Views -Comments · Programming
JavaScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

Recently I needed precision calculations in a project. Native number decimals lose precision (0.1 + 0.2 is not 0.3). So I needed a library. I considered two options and chose mathjs.

big.js

A small, fast JavaScript library for arbitrary-precision decimal arithmetic.

Size: 5.9 KB minified, 2.7 KB gzipped

The size above is from CDN usage.

Pros

  1. Small size

See here

mathjs

Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with different data types like numbers, big numbers, complex numbers, fractions, units, and matrices. Powerful and easy to use.

Size: Unpacked Size 10.2 MB

Pros

  1. Expression parsing

Compatibility

Math.js works on any ES5 compatible JavaScript engine: node.js, Chrome, Firefox, Safari, Edge, and IE11.

See here

Size optimization

  • If you only need numbers, you can import a specific build such as mathjs/main/esm/number instead of full mathjs.

My view

If the calculation is very simple (A * B), big.js is enough. But for complex calculations, big.js hurts readability. mathjs is more readable.

Example

Here is a formula. With mathjs you can write it like this:

But with big.js, it becomes much less readable. Size can be mitigated by CDN and caching, so I chose mathjs.

Final Thoughts

Both work. Use what fits.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover