1

I can't find a good calculator in JavaScript.

In a first time I was using the eval function on my datas to get my result but there were mistakes.

So I found this code:

function calculate(input){

   var f = { add : '+'
       , sub : '-' 
       , div : '/'
       , mlt : '*'
       , mod : '%'
       , exp : '^' };

   // Create array for Order of Operation and precedence
   f.ooo = [[ [f.mlt] , [f.div] , [f.mod] , [f.exp] ],
        [ [f.add] , [f.sub] ]];

   input = input.replace(/[^0-9%^*\/()\-+.]/g,'');           // clean up unnecessary characters

   var output;
   for(var i=0, n=f.ooo.length; i<n; i++ ){

  // Regular Expression to look for operators between floating numbers or integers
  var re = new RegExp('(\\d+\\.?\\d*)([\\'+f.ooo[i].join('\\')+'])(\\d+\\.?\\d*)');
  re.lastIndex = 0;                                     // be cautious and reset re start pos

  // Loop while there is still calculation for level of precedence
  while( re.test(input) ){
     //document.write('<div>' + input + '</div>');
     output = calc_internal(RegExp.$1,RegExp.$2,RegExp.$3);
     if (isNaN(output) || !isFinite(output)) return output;   // exit early if not a number
     input  = input.replace(re,output);
  }
   }

   return output;

   function calc_internal(a,op,b){
  a=a*1; b=b*1;
  switch(op){
     case f.add: return a+b; break;
     case f.sub: return a-b; break;
     case f.div: return a/b; break;
     case f.mlt: return a*b; break;
     case f.mod: return a%b; break;
     case f.exp: return Math.pow(a,b); break;
     default: null;
  }
   }
}

http://jsfiddle.net/vol7ron/6cdfA/

But there are some problems using parenthesis, for example: (10+1)*5 = 11

So I'm trying to find a good calculator in JavaScript to calculate string expressions.

Thanks for your help.

3
  • Google "github calculator javascript" discovers quite a few calculators.
    – Paul
    Aug 9, 2013 at 6:55
  • I can only find simples calculator with html interface
    – Ajouve
    Aug 9, 2013 at 7:00
  • You can find here: sample calculator-application
    – Rain
    Sep 1, 2016 at 9:26

4 Answers 4

3

You can use the math.js library, which comes with a powerful expression parser:

http://mathjs.org

0

I don't have javascript code for it, but general solution how to evaluate complex expresion in string is to convert it using Shunting-yard algorithm into RPN and then use Reverse Polish notation algorithm to get result.

0

This is a solution i recently come up with as an exercise for using clusure in Javascript.

var PocketCalculator = function() {

var allowedOperators = ["+", "-", "*", "/", "="],
    operations = {
        "+": function(a, b) {
            return a + b;
        },
        "-": function(a, b) {
            return a - b;
        },
        "*": function(a, b) {
            return a * b;
        },
        "/": function(a, b) {
            return a / b;
        }
    },
    cache = 0,
    makeOperation = function(b, f) {
        return function() {
            return cache = f(cache, b);
        };
    },
    prevOperation = operations["+"],
    operation = makeOperation(0, prevOperation);
return {
    clear: function() {
        cache = 0;
        prevOperation = operations["+"]
        operation = makeOperation(0, prevOperation);
    },
    push: function(operator, b) {
        if (allowedOperators.indexOf(operator) < 0)
            return;
        if (operator !== "=") {
            prevOperation = operations[operator];
            operation = makeOperation(b, prevOperation);
        } else if (b !== undefined)
            operation = makeOperation(b, prevOperation);
        return operation();
    }
};
};
0
<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>

    <style type="text/css">

    ::selection { background-color: #E13300; color: white; }
    ::-moz-selection { background-color: #E13300; color: white; }

    body {
        background-color: #fff;
        margin: 40px;
        font: 13px/20px normal Helvetica, Arial, sans-serif;
        color: #4F5155;
    }

    a {
        color: #003399;
        background-color: transparent;
        font-weight: normal;
    }

    h1 {
        color: #444;
        background-color: transparent;
        border-bottom: 1px solid #D0D0D0;
        font-size: 19px;
        font-weight: normal;
        margin: 0 0 14px 0;
        padding: 14px 15px 10px 15px;
    }

    code {
        font-family: Consolas, Monaco, Courier New, Courier, monospace;
        font-size: 12px;
        background-color: #f9f9f9;
        border: 1px solid #D0D0D0;
        color: #002166;
        display: block;
        margin: 14px 0 14px 0;
        padding: 12px 10px 12px 10px;
    }

    #body {
        margin: 0 15px 0 15px;
    }

    p.footer {
        text-align: right;
        font-size: 11px;
        border-top: 1px solid #D0D0D0;
        line-height: 32px;
        padding: 0 10px 0 10px;
        margin: 20px 0 0 0;
    }

    #container {
        margin: 10px;
        border: 1px solid #D0D0D0;
        box-shadow: 0 0 8px #D0D0D0;
    }
    </style>




</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
$(document).ready(function(){
    $(".num").click(function(){

        var oprator = $("#val2").val();     
        var one = $(this).val();

        if (oprator=='') {  
        var val1 = $("#val1").val();          
        $("#val1").val(val1+one);
     }else{
        var val1 = $("#val3").val();
        $("#val3").val(val1+one);
     }


    });

    $(".opt").click(function(){

        var plus = $(this).val();
        $("#val2").val(plus);

    });

    $("#equle").click(function(){

        var plus = $("#equle").val();
        var v1 = $("#val1").val();
        var v2 = $("#val2").val();
        var v3 = $("#val3").val();
        var v1int=parseInt(v1);

        var v3int=parseInt(v3);


        if (v2=="+") {
            var z = v1int+v3int;
        }else if(v2=="-"){
            var z = v1int-v3int;
        }
        else if(v2=="*"){
            var z = v1int*v3int;
        }
        else{
            var z = v1int/v3int;
            }

        $("#val4").val(z);

    });

});


</script
<body>

<div id="container">
    <h1>Welcome to CodeIgniter!</h1>

    <div id="body">
    <table>
    <tr cospan="5">
    <td colspan="2"><input type='text' name="val1" value="" id="val1"/></td>
    <td colspan="1"><input type='text' name="val2" value="" id="val2"/></td>
    <td colspan="1"><input type='text' name="val3" value="" id="val3"/></td>
    <td colspan="1"><input type='text' name="val4" value="" id="val4"/></td></tr>
    <tr>

        <td><button type="button" class="num" id="one" value="1">1</button></td>
        <td><button type="button" class="num" id="two" value="2">2</button></td>
        <td><button type="button" class="num" id="three" value="3">3</button></td>
        <td><button type="button" class="num" id="four" value="4">4</button</td>
        <td><button type="button" class="num" id="five" value="5">5</button></td>
   </tr>
   <tr>     
        <td><button type="button" class="num" id="six" value="6">6</button></td>
        <td><button type="button" class="num" id="seven" value="7">7</button></td>
        <td><button type="button" class="num" id="eight" value="8">8</button></td>
        <td><button type="button" class="num" id="nine" value="9">9</button></td>
        <td><button type="button" class="num" id="ten" value="10">0</button></td>
     </tr>  
      <tr>  
        <td><button type="button" id="plus" class="opt" value="+">+</button></td>
        <td><button type="button" id="minus" class="opt" value="-">-</button></td>
        <td><button type="button" id="mul" class="opt" value="*">*</button></td>
        <td><button type="button" id="dev" class="opt" value="/">/</button></td>
        <td><button type="button" id="equle"  value="=">=</button></td>
         </tr>
    </table>    
    </div>


</div>

</body>
</html>
1

Not the answer you're looking for? Browse other questions tagged or ask your own question.