Strange problem in the sum of float numbers

You must Login before you can answer or comment on any questions.

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);
— answered 7 months ago by Arthur Evans
answer permalink
7 Comments
  • i tried so somma = somma + p; somma.toFixed(2);

    but the problem persists

    — commented 7 months ago by nicolò monili

  • toFixed(2) is a method on the Number class that returns the value rounded to two decimal places. So:

    somma = (somma + p).toFixed(2);
    

    Is what you want. Add two floats, round the result, then assign to somma.

    It is not perfect--the BigDecimal class mentioned in Shannon's answer is going to be more accurate. But toFixed is a lot simpler and probably accurate enough if you're primarily doing addition and subtraction.

    — commented 7 months ago by Arthur Evans

  • if i use : somma = (somma + p).toFixed(2);

    message = "'undefined' is not a function (evaluating '(somma + p).toFixed(2)')";

    — commented 7 months ago by nicolò monili

  • Show 4 more comments

Your Answer

Think you can help? Login to answer this question!