最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery multiply and add - Stack Overflow

programmeradmin3浏览0评论

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.)

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.)

Share Improve this question edited Nov 7, 2011 at 11:30 David Laberge 16.1k15 gold badges55 silver badges84 bronze badges asked Nov 7, 2011 at 11:23 dennisbestdennisbest 4192 gold badges5 silver badges10 bronze badges 1
  • 1 jQuery is 100% Javascript. You can use this as usual after getting your values via the element selectors. - Please specify your question further if you need more help. – Smamatti Commented Nov 7, 2011 at 11:24
Add a comment  | 

5 Answers 5

Reset to default 5

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;

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

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.

Correct JQuery is 100% javascript.

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

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

发布评论

评论列表(0)

  1. 暂无评论