Handling decimal operations in Javascript

Don’t we all love Javascript?

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

const preciseOperation = f => (a, b, decimalDigits) => {
  decimalDigits = decimalDigits || 12
  +(f(a, b)).toFixed(decimalDigits)
}
const add  = (a, b) => a + b
const minus  = (a, b) => a - b
const multiply  = (a, b) => a * b
const divide  = (a, b) => a / b
export const preciseAdd = (a, b, decimalDigits) => preciseOperation(add)(a,b, decimalDigits)
export const preciseMinus = (a, b, decimalDigits) => preciseOperation(minus)(a,b, decimalDigits)
export const preciseMultiply = (a, b, decimalDigits) => preciseOperation(multiply)(a,b, decimalDigits)
export const preciseDivide = (a, b, decimalDigits) => preciseOperation(divide)(a,b, decimalDigits)

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.
Like 186 likes
Tino Thamjarat
Share:

Join the conversation

This will be shown public
All comments are moderated

Get our stories delivered

From us to your inbox weekly.