JavaScript中的计算器 [英] Calculator in JavaScript

查看:51
本文介绍了JavaScript中的计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中找不到一个好的计算器.

I can't find a good calculator in JavaScript.

我第一次在数据上使用 eval 函数来获取结果,但是还是有错误.

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/

但是使用括号存在一些问题,例如:(10 + 1)* 5 = 11

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

所以我试图在JavaScript中找到一个好的计算器来计算字符串表达式.

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

感谢您的帮助.

推荐答案

您可以使用math.js库,该库带有一个功能强大的表达式解析器:

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

http://mathjs.org

这篇关于JavaScript中的计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆