-1

I'm trying to convert a calculation String into a Number object in JavaScript, however I can't find a function that do the wanted job.

The parseInt(String) function only parse the first number of calculation but doesn't apply the mathematical functions on it.

I minimal version of what I'm meaning would be something like this: https://jsfiddle.net/qd7u6h60/3/

I'll be glad if someone has an anwser

Xisabla
  • 24
  • 4

3 Answers3

0

alert(eval("12+13+5/5"))

Thats what eval is for. Eval parses valid js, and Math operations are valid JS. Take care on the following

4^4 => is the binary XOR operator
//you want
4**4
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

You need to use eval() instead or parseInt. Updated fiddle: https://jsfiddle.net/qd7u6h60/5/

$('button[name=calculate]').click(function() {
   var calculation = $('input[name=calculation]').val();
   var result = eval(calculation); /* Only parse the first number of the  complete calculation */
   $('input[name=result]').val(result);
});
Spitfire
  • 147
  • 1
  • 5
  • Thanks it works, then I put my question as a duplicate because I saw the question was already asked. – Xisabla Jun 06 '17 at 16:59
0

You can use eval() to compute the value. The eval() function evaluates JavaScript code represented as a string. The argument of the eval() function is a string. If the string represents an expression, eval() evaluates the expression

Please find the code snippet below. I have modified your example

$('button[name=calculate]').click(function() {
var calculation = $('input[name=calculation]').val();
  var result = eval(calculation); /* Only parse the first number of the complete calculation */
  $('input[name=result]').val(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">

<br/>

<div class="input-group">
  <input type="text" name="calculation" class="form-control" placeholder="Calculation, eg: (5 - 2)/(7 + 4)">
</div>

<br/>

<div class="input-group">
  <span class="input-group-addon">=</span>
  <input type="number" name="result" class="form-control" placeholder="Result" readonly>
</div>

<br/><br/>

<button type="button" name="calculate" class="btn btn-info">Calculate !</button>

</div>
Haroon
  • 111
  • 6