Javascript calculator bug

Tell us what’s happening:
I have almost done my project on javascript calculator.
But I have one problem here,Randomly for some input it’s wrong output.
like {8.2 - 2 = 6.199999999999}
whereas,actual answer is {8.2 - 2 = 6.2}
**Edit: LINK to my project: https://codepen.io/Manideep2207/pen/WNrQEeN
You can look into my project to find the bugs.
Any help is appreciated.

Challenge: Build a JavaScript Calculator

Link to the challenge:

Hello and welcome to the FCC community~!

What you have is a floating point problem. You can use JavaScript to parse the float to a specific number of digits, if you want. For example, toFixed(2) returns the number with exactly two decimal places.

Welcome, Manideep.

This is called floating point error, and it a memory limitation with computation. The solution is usually to round the answer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

Hope this helps

1 Like

Thanks for the reply mate,
My problem is still unsolved.
I don’t want my answer to be restricted to fixed decimal places.
for example I want this {8.2 - 2.2 = 6}
but my calculator is displaying {8.2 - 2.2 = 5.9999999999999}.
Help me if you have any better solution.

Thanks for the reply mate,
But I don’t want my answer to be restricted to integers.
I want exact real number.
Help me if you have any better solution.

In vanilla JavaScript, I’m not aware of a simple solution to accomplish this.
You could check the decimal length of each inputted number, then toFixed() based on that length. But that’s a little bit of a convoluted process.