DEV Community

Discussion on: JavaScript Calculator - The DOM way

Collapse
 
thi3rry profile image
Thierry Poinot

You should check out this article dev.to/nicozerpa/javascript-has-a-...
To fix operations with decimals ;)

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

Hahaha Hi Thierry! Did you really check how much precision it has?

I mean, I stored the numbers in Strings, which is something you usually do when seeking precision -depending on the workaround- but I honestly didn't check for that. It was like, .0034 + .0066 = 0.01 -> Check!

The "bad thing" I did there is not the precision but the use of eval() as I do in the codepen. Check eval can be harmful if you are going to use it on any place.

Thank you for sharing, Decimal.js, Bigdecimal.js, Big.js and Bignumber.js, are libs that we'all should know that they exist at least, we may need them at any time 😊

Collapse
 
thi3rry profile image
Thierry Poinot

Actually, i read this article few days ago and I was amazed about this issue of JS, so when I saw you calculator I just test it to know and share to you and your readers these libs ;)

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

Hahaha I'ts ok. Just remember that is not a "Javascript issue" but an issue of the binary base we have most of the time.

In most programming languages, floating point numbers are represented a lot like scientific notation: with an exponent and a mantissa or significand.

A very simple number, say 9.2, is actually this fraction:
5179139571476070 * 2-49
Where the exponent is -49 and the mantissa or significand is 5179139571476070.

The reason it is impossible to represent some decimal numbers this way is that both the exponent and the mantissa must be integers. In other words, all floats must be an integer multiplied by an integer power of 2.

9.2 may be simply 92/10, but 10 cannot be expressed as 2n if n is limited to integer values (23=8 and 24=16).

Image description

This is information gathered from a pair of comments in SO with some annotations added in a vague try to make it more understandable, because honestly I don't feel myself skilled enough on this mathematical topics to explain it by my own without spending days in previous research and doing diagrams, examples and so.

You can check the original comments here.

Some comments have been hidden by the post's author - find out more