Handling decimal operations in Javascript

Don’t we all love Javascript?

Tino Thamjarat
The OOZOU Blog
2 min readAug 22, 2017

--

I ❤ Js

The most annoying thing when you have to do some math operation in Javascript is that sometimes it does not work the way you want.

Take a look at this example

0.1 + 0.2 //0.30000000000000004

What is going on here?

This is not Javascript acting weird but it’s just the nature of how computers work. Computers internally use binary floating point to denote decimal. Unfortunately, it cannot accurately represent numbers like 0.1, 0.2 or 0.3 at all.

Read more here http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/

Try any programming language without Decimal Datatype . This is a common issue.

Solution

There are several approaches one can take to tackle this problem. Using a library such as https://github.com/MikeMcl/decimal.js/ is a pretty decent choice. However, I only want to do a simple math operation (+ , — , x, %) and I think using that lib is a bit overkill.

I decided to write my own preciseMath.js and here is how it looks

The code does a simple rounding with a nice little touch that you could also specify decimal digits precision as the last argument. The default is 12 digits.

import { preciseAdd } from 'preciseMath'preciseAdd(0.1, 0.2) //0.3

All in all, this is the approach I came up with which is pretty simple and easy to follow. It might not be the cleanest code (please help fix!) and I would like to see your solution too. Feel free to show them in the comment section.

References

Shy me.

Thank you for reading

My name is Tino Thamjarat. Technical Lead at BASE and Software Engineer at Oozou . I love discussing everything. Business ideas, philosophy, physics, religion, tech, gaming, you name it. I also play League of Legend and a little bit of music once in a while. If you need a website, want to give some advice/comments or just need some guy to talk to, feel free to contact me on my Twitter or Instagram.

P.S. Hit that clap button to show some ❤

--

--

Tino Thamjarat
The OOZOU Blog

Engineer at GoJek. CTO at BASE Playhouse. I love building good software so I do it for a living. ❤