js的加减乘除
2021年08月31日 | 作者: xaoi | 分类: js | 评论: 0 | 浏览: 1007
var a = xaoi.calc('0.1 + (0.2 - 0.5) * (2 - 0.06)-3') console.log(a) a = xaoi.calc('0.09+0.2') console.log(a)
if(typeof xaoi === 'undefined')xaoi = {} xaoi.calc = function(data){ var jia = function(a,b){var c,d,e;try{c=a.toString().split(".")[1].length}catch(f){c=0}try{d=b.toString().split(".")[1].length}catch(f){d=0}return e=Math.pow(10,Math.max(c,d)),(chen(a,e)+chen(b,e))/e}; var jian = function(a,b){return jia(a,-b)} var chen = function(a,b){var c=0,d=a.toString(),e=b.toString();try{c+=d.split(".")[1].length}catch(f){}try{c+=e.split(".")[1].length}catch(f){}return Number(d.replace(".",""))*Number(e.replace(".",""))/Math.pow(10,c)}; var chu = function(a,b){var c,d,e=0,f=0;try{e=a.toString().split(".")[1].length}catch(g){}try{f=b.toString().split(".")[1].length}catch(g){}return c=Number(a.toString().replace(".","")),d=Number(b.toString().replace(".","")),chen(c/d,f>e?Math.pow(10,f-e):parseFloat('0.'+(new Array(-(f-e)).join('0'))+'1'))}; var f1 = function(str){ var re = /([\+\-\*\/])/g; var match,cursor = 0,code = []; while(match = re.exec(str)) { code.push([ str.slice(cursor, match.index), match[1] ]); cursor = match.index + match[0].length; } code.push([ str.slice(cursor, str.length), null ]); return code; } var f2 = function(str){ var arr = f1(str); var cc = function(i){ if(arr.length === i)return; if(arr[i][1] === '*' || arr[i][1] === '/'){ arr[i+1][0] = arr[i][1] === '*'?chen(arr[i][0],arr[i+1][0]):chu(arr[i][0],arr[i+1][0]) arr.splice(i,1); cc(i); }else{ cc(i+1); } } var jj = function(i){ if(arr.length === i)return; if(arr[i][1] === '+' || arr[i][1] === '-'){ arr[i+1][0] = arr[i][1] === '+'?jia(arr[i][0],arr[i+1][0]):jian(arr[i][0],arr[i+1][0]) arr.splice(i,1); jj(i); }else{ jj(i+1); } } cc(0); jj(0); return arr[0][0]; } var f3 = function(str){ var num = 0; var f = function(){ var d = /\(([^\)]+)\)/.exec(str); if(d){ str = str.substr(0,d.index)+f2(d[1])+str.substr(d.index+d[0].length); f(); } } f() return f2(str); } data = data.split(/\s+/).join('') if(!data.length)return 0; data = f3(data); return data; }
顶一下 ▲()
踩一下 ▼()
发表留言
登录后才能发表留言,立即 登录 或 注册
提交 (Ctrl+Enter)