1

This code must give the output of the total cash , but rather gives wrong output? Can anybody please tell me what is wrong in it.

var cashRegister = {
   total:0,
   add: function(itemCost)
   {
      this.total += itemCost;
   }
};

var i;

for (i=0; i<4; i++)
{
   var a = prompt("Cost");
   cashRegister.add(a);
}
//call the add method for our items


//Show the total bill
console.log('Your bill is '+cashRegister.total);
1
  • It would help to show what the actual vs. expected output is. And if you actually looked at the actual output, I think you would get a pretty good hint ;) Commented Jan 26, 2014 at 11:49

6 Answers 6

3

Your adding strings.

instead of:

this.total += itemCost;

try:

this.total += +itemCost;
Sign up to request clarification or add additional context in comments.

Comments

3

You need to parseInt your input values because they are strings and you'll only concat them that way. So, try:

this.total += parseInt(itemCost, 10);

See here: http://jsfiddle.net/3x9AH/

Comments

0

You can try with:

add: function(itemCost)
{
   this.total += parseInt(itemCost);
}

Comments

0

You are attempting to add strings.

You should convert to a number, but be careful with arbitrary user input.

For example, none of the other answers will take into account the following inputs:

  1. "foo"
  2. "+Infinity"
  3. "-Infinity"

Change this line:

this.total += itemCost;

to:

this.total += itemCost >> 0;

Comments

0

Use parseFloat() function, it used to parses a string argument and returns a floating point number.

this.total += parseFloat(itemCost);

Comments

-1

The problem you have is that you are adding strings instead of numbers.

You can do something like this to fix it: this.total += Number(itemCost);

http://jsfiddle.net/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.