JavaScript - Fixing that da*n caret symbol for calculator

女生的网名这么多〃 提交于 2019-12-06 11:56:56

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

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