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 56
but instead is giving 4817
. 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 4817
.
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.
EDIT
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));
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…