0

I have a input field where user can write equation like 3+4-2 etc. Using jquery I can retrieve the value of input field like this:

var eqn = $("input").val();

Variable eqn contain 3+4-2, I have to display it as 5(by solving) not as 3+4-2. How to display the equation as result? Equation may contain the symbols +,-,*,/,. etc.

Since the variable eqn is string type it display as 3+4-2. When I use parseFloat it display as 3. So this can't be use.

Deepu Sasidharan
  • 5,193
  • 10
  • 40
  • 97

2 Answers2

0

I've done some research in the related question: Evaluating a string as a mathematical expression in JavaScript

There appears to be a locked-down version of the javascript 'eval' method which exposes the maths functionality but not the entire JS API to a user in the mathjs library. Which allows statements like this:

math.eval('1.2 * (2 + 4.5)');
Community
  • 1
  • 1
AJFaraday
  • 2,411
  • 1
  • 16
  • 39
-3

Write code using eval

eval('3+4-2')

  • 1
    This would be a very insecure way of handling user input. Which could easily break the application. Fortunately, client-side javascript rarely has access to a file system, OS or other applications which could do any real harm, and all attacks of this type could be attempted from a browser console. – AJFaraday May 28 '15 at 10:30
  • 2
    I think You're missing @AJFaraday 's point... You should at least investigate if that function protects against things it shouldn't be allowed to do. – Carlos Bribiescas May 28 '15 at 10:34
  • The basic concern here is what else you can do with it, because you're evaluating javascript here, not just the mathematical functions. Try typing this... "alert('this is not secure')" – AJFaraday May 28 '15 at 10:52
  • 2.1+3.2 gives 5.300000000000001, but expected is 5.3 – Deepu Sasidharan May 28 '15 at 10:52
  • He already did, see the second comment to your question. As for the floating point issue see http://stackoverflow.com/questions/588004/is-floating-point-math-broken – JJJ May 28 '15 at 10:57
  • I think there may have been some confusion here with a floating point issue in javascript. I'm putting in a suggested answer. – AJFaraday May 28 '15 at 11:04