4.I Have to Scan It More Than Once?


#1

What's wrong with this? My console prints 'Your bill is 30.600000000000005' and not 30.6... Why?

//Show the total bill
console.log('Your bill is '+cashRegister.total);


var cashRegister = {
    total:0,
    add: function(itemCost){
        this.total += itemCost;
    },
    scan: function(item,quantity) {
        switch (item) {
        case "eggs": this.add(0.98 * quantity); break;
        case "milk": this.add(1.23 * quantity); break;
        case "magazine": this.add(4.99 * quantity ); break;
        case "chocolate": this.add(0.45 * quantity ); break;
        }
    }
};

cashRegister.scan("eggs",4);
cashRegister.scan("magazine",4);
cashRegister.scan("milk",4);
cashRegister.scan("chocolate",4);// scan each item 4 times



//Show the total bill
console.log('Your bill is '+cashRegister.total);


#2

You can fix it:

this.total += itemCost.toFixed(2);

I found some information about this problem:
1. Weird Javascript Behaviour
2. Is floating point math broken?


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.