dennisbest
dennisbest

Reputation: 419

JQuery multiply and add

Let's say I have some numbers that I want to multiply and add.

var a = 5;
var b = 10;
var c = 2;
var d = 3;

I want to sum b and c then multiply that by a, then add d. Easy right?

If if were a normal equation the formula would look like: (a * (b + c) + d)

But how do I do that in JQuery?

(Note: the reason for JQuery is that I'll be getting these numbers from fields and divs... and placing a total elsewhere, etc.)

Upvotes: 3

Views: 29513

Answers (5)

David Laberge
David Laberge

Reputation: 16051

By default script language does not know type as int or float. So you can fix that by multiplying 1 to the value you expect to be a number.

var a = 5;
var b = 10;
var c = 2;
var d = 3; 

var total = a*1 * (b*1 + c*1) + d*1;

Upvotes: 5

Anand
Anand

Reputation: 14915

Correct JQuery is 100% javascript.

Although, worth mentioning just use parseint() for the values that you get from text field

Upvotes: 2

Marius
Marius

Reputation: 58931

Just store the values in variables before you apply them to the equation:

var a = +$("#input1")[0].value;
var b = +$("#input2")[0].value;
var c = +$("#input3")[0].value;
var d = +$("#input4")[0].value;

$("#output")[0].value = a*(b+c) + d;

The plus sign before the jquery function is there to force the string value into a Number value.

Upvotes: 3

psx
psx

Reputation: 4048

You can still do the calculation using normal javascript, just refer to the contents using jQuery selectors if necessary.

Upvotes: 1

You Qi
You Qi

Reputation: 9211

convert your value into float or integer first before you do calculation. Example:

var a = parseFloat($(this).val());
var b = parseInt($("#b").attr("data"));

var c = (a+10)*b;
$("#result").text(c.toFixed(2));

Upvotes: 4

Related Questions