tonyf
tonyf

Reputation: 35537

JavaScript math calculation

I need to perform a math calculation in JavaScript that I am unsure how to do so.

The formula is as follows:

result = (scale * weighting) / 2

where the result I will need to two decimal places.

Example formula that I need to do in JavaScript might be:

result = ((3 * 2) + (2 * 1.5)) / 2

I am also unsure if I have to also convert this to int.

Upvotes: 0

Views: 3050

Answers (3)

sreekarun
sreekarun

Reputation: 41

In JavaScript everything number is a floating point number. No explicit type conversion needed.

ref : http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html ( search for "The Number Data Type" )

Upvotes: 0

Richard Dalton
Richard Dalton

Reputation: 35793

Not entirely sure what you want, but this might help:

result = Math.round(((scale * weighting) / 2) * 100) / 100;

http://jsfiddle.net/kQpma/

Upvotes: 0

Joe
Joe

Reputation: 82584

toFixed:

function algorithm(scale, weighting) {
   var result = (scale * weighting) / 2;
   return result.toFixed(2);
}

Or if you need an integer, parseInt:

parseInt(result, 10);

Upvotes: 6

Related Questions