Sitemap
devinred 🎈

devinred 🎈

I'm interested in many things, but only briefly. Then, I need to switch things up - whether it's the project, language, or even keyboard https://devinred.com

Weird Math in JavaScript

Overcoming common calculation errors with simple techniques and libraries

1 min readJun 14, 2024

--

Simple math isn’t always as simple as it seems.

Press enter or click to view image in full size
Photo by iSawRed on Unsplash

Remember the solar calculator? The one you can buy for less than 1 euro? That seemingly outdated piece of technology is actually better at math than Node.js.

A well-known example is:

0.1 + 0.2 = 0.30000000000000004

I won’t dive into the technical details of why this happens. Instead, I’ll explain two straightforward ways to solve this issue:

  1. Using integers
  2. Using a library

Using Integers

Convert the numbers to integers before performing the calculation:

(0.1 * 100 + 0.2 * 100) / 100 = 0.3

Using a Library

While you can do math without a library, in some applications, precision is critical. To simplify the task, I recommend using mathjs. It's as simple as using an old solar calculator.

Get devinred 🎈’s stories in your inbox

Join Medium for free to get updates from this writer.

First, install and configure mathjs:

import { create, all } from 'mathjs'

const config = {
number: 'BigNumber',
precision: 20
}
const mathjs = create(all, config)

Then, you can perform calculations by evaluating expressions as strings:

mathjs.evaluate('0.1 + 0.2'); // Returns 0.3

If you have variables, it’s just as easy:

let a = 0.1;
mathjs.evaluate(`${a} + 0.2`); // Returns 0.3

And that’s all there is to it.

--

--

devinred 🎈

Written by devinred 🎈

I'm interested in many things, but only briefly. Then, I need to switch things up - whether it's the project, language, or even keyboard https://devinred.com