Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As mentioned in the comments, expression Math.floor(("90"+"15") * (0.5343543)); gives 4817


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...