Javascript - calculation including either "*" or "/" gives me a wrong answer
I wrote a javascript code that generates a calculation formula at random.
The code generates something like these at random.
134 + 333 = 467
10 * 3 = 30
9 / 3 = 3
130 - 20 = 110
In order to generate something like these, I have this code as shown below.
var myCal = [
function(a, b){return a + b;},
function(a, b){return a - b;},
function(a, b){return a / b;},
function(a, b){return a * b;}
];
var tempX = parseInt(Math.random()*1000),
tempY = parseInt(Math.random()*1000),
tempNum = parseInt(Math.random()*4),
result;
result = myCal[tempNum](tempX, tempY);
But, the problem is that when it generates calculation formula including
either "*" or "/", it returns wrong answer.
For example, when tempX is 393 and tempY is 334 and operator is *, it
returns 1.1766467065868262.
What's causing this problem?
I have no clue of what's wrong with it.
Please help me out if you know how to solve this problem.
Thanks!!
P.S
Since I'm building a Chrome extension, I'm not allowed to use the eval
function by their security policy. That's why I have my own myCal
function.
No comments:
Post a Comment