4/7 I Have to Scan It More Than Once?


#1

I can't seem to find what I'm doing wrong. I get the message:
"Oops, try again. Did you scan four of each item?"

Here is my code can anyone help?

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;
        }
    }
};

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

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

#2

@ludicucek,
Try scanning in a different order....

cashRegister.scan("eggs", 4);
cashRegister.scan("milk", 4);
cashRegister.scan("magazine", 4);
cashRegister.scan("chocolate", 4);

#3

That worked, thanks. :smile:


#4

@leonhard_wettengmx_n

Maybe you can tell me why we have here this side effects?

What is the difference here?

I can see that the result is 30.6 in my code, his code give the result 30.600000000000005


#5

@dookoo_de,
well to be honest, as one would say, this goes way past my pay-grade...
I can only demonstrate....

eggs 		3.92 <== 3.92
milk 		8.84 <== 4.92
magazine 	28.8 <== 19.96
chocolate 	30.6 <== 1.8
Your bill is 30.6

eggs 		3.92		   <==  3.92
magazine 	23.880000000000002 <== 19.96
milk 		28.800000000000004 <== 4.92
chocolate 	30.600000000000005 <== 1.8
Your bill is 30.600000000000005

eggs 		3.92	 <== 3.92
chocolate 	5.72	 <== 1.8
magazine 	25.68	 <== 19.96
milk 		30.6	 <== 4.92
Your bill is 30.6

console.log( 5.77 + 19.96); ==> 25.73
console.log( 5.78 + 19.96); ==> 25.740000000000002

google search
== discussions / opinions ==
javascript strange behaviour number site:stackoverflow.com
= http://stackoverflow.com/questions/1036662/weird-javascript-behaviour-floating-point-addition-giving-the-wrong-answer


4/7 Cash register totals at 30.600000000000005