user1512166
user1512166

Reputation: 21

Javascript Calculation not working properly

Hello I am trying to do a simple calculation of three values: a + b * c but getting wrong total. If a is 10 and b is 10 it would be 20 multiplied by c which is 2.4. I should get 48 as total. Currently getting 2424.

function compute() {
  var a = $('#a').val();
  var b = $('#b').val();
  var c = $('#c').val();
  var total = (a + b) * c;
  $('#total').val(total);
}

$('#a, #b, #c').change(compute);

Upvotes: 0

Views: 119

Answers (6)

Sibu
Sibu

Reputation: 4617

$(document).ready(function() {
   function compute() { 
          var a = $('#a').val();
          var b = $('#b').val();
          var c = $('#c').val();
          var total = (parseInt(a,10) + parseInt(b,10)) * parseFloat(c); alert(total);
          $('#total').val(total);
        }

  $('#a, #b, #c').change(compute);

 });

Check DEMO

Upvotes: 0

Wahaj Ahmed Ansari
Wahaj Ahmed Ansari

Reputation: 263

try after parsing the values like: var total = (parseFloat(a) + parseFloat(b)) * parseFloat(c);

Upvotes: 0

Damask
Damask

Reputation: 1254

Your variables are strings. Use parseFloat function.

"10" + "10"*"2.4" = "10"+ 24 = "1024"

Upvotes: -2

Luc Morin
Luc Morin

Reputation: 5380

If you want to add a to b BEFORE multiplying, you'll need to use parentheses.

That's because the multiplication oprator has higher precedence than addition.

(a + b) * c

Upvotes: 1

Anirudh Ramanathan
Anirudh Ramanathan

Reputation: 46728

a + b * c is being evaluated as a + (b * c)

What you need is (a + b) * c

Precedence: Brackets > Division > Multiplication > Addition > Subtraction


In your question, you stated that you get 1024. Getting 1024 is impossible. You should get 34. (Check your calculation elsewhere)

a + (b * c) = 10 + (10 * 2.4) = 34

Upvotes: 1

pistache
pistache

Reputation: 6203

Basic maths : multiplication have precedence over addition.

So in your code, a is additionned to the result of b*c .

Use :

var total = (a + b) * c;

Upvotes: 1

Related Questions