FatalKeystroke FatalKeystroke - 1 year ago 76
Javascript Question

Javascript equation producing incorrect value

I have a Javascript function which returns a result based on variables passed to it. It is giving incorrect values during calculation however.

I've narrowed the culprit to here:

Math.floor((obj.mem1.val1 + i) * (obj.mem2[param][j].val2))

Which when replacing the variables from the code with their numeric values (yes, I've checked to ensure they are the correct values being passed to the equation) it is:

Math.floor((90 + 15) * (0.5343543))

Which should come out to equal
but instead is giving
. I've even added in:

alert(Math.floor((90 + 15) * (0.5343543)))

Just to see if making the browser run the exact calculation manually yields the right number, but it still gives an alert box saying

What could possibly be doing this? It's doing basic math wrong. Something I've always kind of trusted a computer to do correctly without fail.


Sample code to show the error:

var obj = {
"mem1": {
"val1": "90" // <-- issue was ultimately here this value was being
// populated from
// document.getElementById().innerHTML
// elsewhere in the code, so it was saving a string
"mem2": {
"something-passed-through-param": [
{ "val2": 0.5343543 }

function func(param, i, j) {
var ret = Math.floor((obj.mem1.val1 + i) * (obj.mem2[param][j].val2));
return ret;

// Correct code would have been:
var ret = Math.floor((Number(obj.mem1.val1) + i) * (obj.mem2[param][j].val2));

Answer Source

Per the comments, the issue was that obj.mem1.val1 was being passed to the calculation as a string, resulting in ('90' + 15) * (0.5343543) or more likely ('90' + 1) * (0.5343543). Casting it to a number corrects the issue. This may be done like so:

Math.floor((+obj.mem1.val1 + i) * (obj.mem2[param][j].val2))


Math.floor((Number(obj.mem1.val1) + i) * (obj.mem2[param][j].val2))

and a few other ways.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download