JavaScript - Fixing that da*n caret symbol for calculator

百般思念 提交于 2019-12-07 20:56:11

问题


I'm making a calculator in javascript and as of now it calculates: sin, cos, tan, cot, sec, csc and also arc and hyberbolic of all subtypes, sqrt, cbrt, y-th root, and pow. The problem is that I dont want to have the pow(x,y) as a function, I want to be able to type in for example:

2^3+2^4 # instead of pow(2,3)+pow(2,4)

How do I go about to get the function typed in as shown above? Here's the calculator for viewing it: http://calcy.comze.com/


回答1:


I assume you have the formula in a string. Here is how you can do it:

Extend the numbr proto to have a pow method:

Number.prototype.pow = function(n){
   return Math.pow(this,n);
}

wrap every number around () and replace ^ with .pow()

str = str.replace(/[\d|\d.\d]+/g, function(n){
   return '(' + n + ')'
})
.replace(/\^/g, '.pow')

Eval the string

eval(str)

Working example: http://jsbin.com/igegok/1/edit




回答2:


You can transform your ^ notation to pow function, or Math.pow with regexp:

'2.14^3+ 2^2.5 - 12'.replace(/(\d+(?:\.\d+)?)\^(\d+(?:\.\d+)?)/g, function(a, b, c) {
    return 'pow(' + b + ', ' + c + ')';
})
// pow(2.14, 3)+ pow(2, 2.5) - 12

With this approach you can even precalculate the power result and replace carots like this:

'2^3+ 2^2.5 - 12'.replace(/(\d+(?:\.\d+)?)\^(\d+(?:\.\d+)?)/g, function(a, b, c) {
    return Math.pow(b, c);
});
// 8+ 5.656854249492381 - 12


来源:https://stackoverflow.com/questions/15037805/javascript-fixing-that-dan-caret-symbol-for-calculator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!