Hello to all you guys! I encountered a strange problem while the sum of float numbers. Basically I have a function here in step two values, the function takes the first of these values ??and adds it to the previous ones passed. The problem is that the sum of the float numbers is not correct ... for example by adding 6.90 + 6.90 + 6.90 is 20.700000000000003 ..
this is my function...
addCart.addEventListener('touchend', function(e) { if (e.source.id == 0) { nome = "Pizzaccia Chef"; prezzo = 6.50; nuovaRow(nome,prezzo); } . . .
function nuovaRow(n, p) { //Ti.API.info(p.replace(' €', '')); somma = somma + p; tot.text = "Tot : " + somma + " €"; . . .how can I solve this problem?
2 Answers
This is the nature of floating-point math. It can't precisely represent all numbers, so errors are introduced. See, for example, Wikipedia on Floating Point Accuracy Problems.
You can use toFixed to round to the appropriate number of digits:
somma = (somma + p).toFixed(2);
Your Answer
Think you can help? Login to answer this question!