Weird Math in JavaScript
Overcoming common calculation errors with simple techniques and libraries
Simple math isn’t always as simple as it seems.
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.30000000000000004I won’t dive into the technical details of why this happens. Instead, I’ll explain two straightforward ways to solve this issue:
- Using integers
- Using a library
Using Integers
Convert the numbers to integers before performing the calculation:
(0.1 * 100 + 0.2 * 100) / 100 = 0.3Using 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.3If you have variables, it’s just as easy:
let a = 0.1;
mathjs.evaluate(`${a} + 0.2`); // Returns 0.3And that’s all there is to it.






