PDA

View Full Version : JavaScript Calculator: Parentheses

Mr. Larsen
Jul 25th, 2011, 11:26 PM
I need help putting parentheses in my calculator. Could anyone provide me some source code for parentheses in a calculator?

If not source code, could you offer me recommendations as to how to solve my problem? Thanks!

maxhud
Jul 25th, 2011, 11:29 PM

Philip M
Jul 26th, 2011, 12:27 PM
If you ask JavaScript (or any programming language) to perform a calculation using multiple operators, those operators will be evaluated in a specific order. For example 3 + 6 * 7 is calculated as ( 6 * 7 ) + 3 because the * is calculated before the +. The order in which these are evaluated is: * / % + - + (where the second + is appending strings). To change the order in which they are calculated, use parenthesis ( ) as the contents of parenthesis are calculated before the contents outside the parenthesis. For example, 3 + 6 * 7 = 45 but ( 3 + 6 ) * 7 = 63.

If this explanation is insufficient, try Google.

All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

maxhud
Jul 26th, 2011, 08:45 PM
Do you want to make it so that you can change the order of operations with parentheses?

For example, if you were using 4 + 2 * 5 and wanted to add 4 to 2 and then multiply that (6) by 5, then it would look like this: (4 + 2) * 5

If so, you can make a string "(4 + 2) * 5"

And then do

var equation = "(4 + 2) * 5";
var answer = parseInt("(4 + 2) * 5");