-5

I am trying to make a calculator of sorts, and I want this feature. example: you write this in input: '2^(2)' I want it to put 2 to the power of whatever is in the parentheses after the ' ^ '

Baki
  • 1
  • 1
  • 2
  • 2
    What code have you tried? – Scott Marcus Jun 18 '17 at 18:24
  • did u try anything ? – Riaz Laskar Jun 18 '17 at 19:52
  • Yes, it works fine, for this format "x^(y) ", but I need something that will work with no specific format like this: "1+x^(y)+1" and if the x = 2 and y = 2, answer will be: "1+2^(2)+1" = 6 @Riaz – Baki Jun 18 '17 at 21:49
  • HTML `

    `
    – Baki Jun 18 '17 at 21:50
  • Script ` var $ = function(id){ return document.getElementById(id);}; function powr(){ var input = $("input").value; var params = input.split("\^"); var num_base = params[0]; var power = params[1].replace("(", "").replace(")", ""); var rez = Math.pow(num_base, power); p.innerHTML = rez; }` – Baki Jun 18 '17 at 21:51

1 Answers1

0

It is quite simple solution:

var input = "2^(2)";
var params = input.split("\^");
var num_base = params[0];
var power = params[1].replace("(", "").replace(")", "");
var rez = Math.pow(num_base, power);

You can achieve this also by using regular expressions.

EDIT: changed from Java to Javascript, due to human error

Miha Jamsek
  • 1,193
  • 2
  • 17
  • 33
  • Why do you assume Java when question is not tagged with Java, but is tagged with JavaScript? – Scott Marcus Jun 18 '17 at 18:28
  • I somehow missed it - fixed now – Miha Jamsek Jun 18 '17 at 18:37
  • 1
    How do you do the same thing, but now with input like: 1+2^2, where order of operation matters. – Baki Jun 18 '17 at 18:48
  • if you know that there is fixed format, then you can use it by same procedure as i stated in the answer. split by +, then you have element 0 as your first number and element 1 is string which you process as i stated in answer. however, if you need to parse a mathematical expression, without prescribed format, then it is a bit harder to do. similiar problem in java: https://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – Miha Jamsek Jun 18 '17 at 18:55
  • I have no fixed format, so how would I do it in javascript? – Baki Jun 18 '17 at 19:05
  • I recommend to first search for things like that, as this was the first result on google. (btw, you can accept my answer if it solved your (asked) problem). Here is expression evaluation in javascript: https://stackoverflow.com/questions/2276021/evaluating-a-string-as-a-mathematical-expression-in-javascript – Miha Jamsek Jun 18 '17 at 19:11