user image

Published in : 2022-02-26

Javascript Add (+) issue


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?


Shilpa Date : 2022-02-27

Best answers


Best answers


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.


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.

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

Help: How do I loop simple JSON objects to iterate all keys and values itself?
Publish date: 2022-03-06 | Comments: 1

Tag: Javascript

How to get audio input and audio output as one stream?
Publish date: 2022-02-13 | Comments: 2

Tag: Javascript

How to open URL in new tab & focus on it in Javascript?
Publish date: 2021-12-22 | Comments: 1

Tag: Javascript

How select specific tag in jQuery using if else statement?
Publish date: 2022-02-27 | Comments: 1

Tag: Javascript

javascript: Uncaught TypeError: undefined is not a function
Publish date: 2022-03-02 | Comments: 2

Tag: Javascript