 Rakshit

26 Feb 2022

Javascript

My Client is explaining about minor javascript issue as we are working with cryptocurrencies:  (Replicated issue Link)

If I have 0.1 BTC in my first wallet and 0.2 BTC in my other wallet, I want to calculate the total using the javascript + (Add) feature.

Simply I am adding an array of all available wallets.

If I do, 0.1+0.2 = 0.30000000000000004 BTC

It should Show 0.30000000000000000 BTC liters overall!

What could be the solution to get an exact 0.3 BTC properly?

Find Fault here: codepen Shilpa

27 Feb 2022  That error occurred because of the floating-point mechanism about how do they store values. That's why it feels like floating-point math is broken up!

``````If you check 0.1 + 0.2 == 0.3
It will return false.
Reason: Neither 0.1 nor 0.2 are exactly representable in binary floating points logic. And nor is 0.3!
Binary floating points logic: The number is split into three parts, sign, exponent and fraction, when stored in binary.``````

You can see IEEE 754 Standards here on wikipedia.

When you write 0.1, it means 1/10. As per binary64 format,

``````The decimal value will become 0.100000000000000005551…
The hex float notation will become 0x1.999999999999ap-4``````

Always remember,

• The more operations you do on a floating-point number / numbers, the more significant rounding errors can occur.

Solution:

You can use round(number, k) and Ceiling Function for such decimal numbers, so you don't have to get BTC from your pocket. You can also use below equivalent logic too.

``String myNumberString = String.format("%1.1d", Double.valueOf(myNumber));``

Hope this helps you.