Strange results when adding / subtracting floats in Javascript

I am experimenting with JavaScript for the first time. My goal is to create a small "configurator". There are two buttons on my page that launch the following onclick functions:

 function default() { curPrice = parseFloat(document.getElementById('price').innerHTML); newPrice = curPrice-priceEngraving; document.getElementById('price').innerHTML=newPrice; } 

and the other is as follows:

 function engrave() { var str = document.getElementById('price').innerHTML; newPrice = curPrice+priceEngraving; document.getElementById('price').innerHTML=newPrice; } 

priceEngraving defined as 1, and the "default" innerHtml from #price is 5.30. When button 1 is pressed, the following result appears:
6.3

This is normal and the expected result (adding 0 to the end is not too complicated).

When button # 2 is pressed, the following result appears: 5.3000000000000004

I do not know where the problem is in my code. I also tried ++ and -- (which I don't prefer, because, as you know, prices are subject to change).

In addition, I know about security issues when using JavaScript, but this one is just optical.

+4
source share
2 answers

The problem is that some numbers cannot be represented exactly as floating point numbers. If you always want 2 decimal places, you can use the toFixed(2) method ( documentation ) on your numbers.

 document.getElementById('price').innerHTML=newPrice.toFixed(2); 
+1
source

You have floating point problems. See this post for more details, questions are discussed in detail. In principle, there is no way to compare what you have quite accurately.

0
source

Source: https://habr.com/ru/post/1439462/


All Articles