Convert Decimals to Integers Before Adding, Subtracting, Multiplying or
Dividing Them
I put together a basic calculator where the user can type their equation
into a text box and click solve. Any equation that includes addition,
subtraction, multiplication and/or division can be entered example:
1*2+18/2+(7+2)
The problem is when decimals are used. I've found that there's no simple
solution in JavaScript or jQuery to handle them in the context of a
calculator. Every single JavaScript calculator tutorial doesn't work
correctly with decimals.
I think the best way to handle them is to convert them to integers? I
thought about multiplying the decimals by 100000, doing the math, then
dividing by 100000 but this only works with addition and subtraction. What
method would work to convert decimals to integers when the equation
contains mixed operations such as 1*2+18/2+(1.2 + 0.64) then convert it
back?
Fiddle: http://jsfiddle.net/4F27z/
HTML
<input type="text" id="userProblem" size="100">
<input type="submit" id="solveButton" value="Solve">
<div id="answerDiv"></div>
JavaScript
solveButton.onclick = function () {
var answer = eval(userProblem.value);
answerDiv.innerHTML = answer;
};
No comments:
Post a Comment