2

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;
};
user1822824
  • 2,478
  • 6
  • 41
  • 65
  • What do you mean by "doesn't work correctly with decimals"? Have you looked at the [`parseFloat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) function? – Donut Sep 09 '13 at 18:02
  • @Donut What I'm getting from the question is that the calculator implementations he's looking at don't take floats into account. Either he would have to add it himself, or take a different approach. –  Sep 09 '13 at 18:03
  • 3
    The fiddle works fine for me with decimals, including `1*2+18/2+(1.2 + 0.64)`. Can you provide an example where it doesn't work? – Ted Hopp Sep 09 '13 at 18:04
  • 3
    "The problem is when decimals are used. [PLEASE ADD A SIMPLE, REPRODUCIBLE EXAMPLE HERE]." Are you complaining about broken floating point, like when `0.1-0.01 = 0.09000000000000001` ? – Paul Sep 09 '13 at 18:04
  • Javascript only has floating point values, so converting to integers will not solve anything because you're just changing the position of the decimal point. – Matt Bryant Sep 09 '13 at 18:06
  • 1
    Take a look here. http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken this answer your problem. – avrahamcool Sep 09 '13 at 18:06

0 Answers0