...

View Full Version : JavaScript Calculator: Parentheses



Mr. Larsen
07-26-2011, 12:26 AM
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
07-26-2011, 12:29 AM
Could you explain your problem more please?

Philip M
07-26-2011, 01: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
07-26-2011, 09: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");
alert(answer);

jmrker
07-27-2011, 03:43 AM
Works better without the '"' around the string. :thumbsup:


<script type="text/javascript">
var equation = "(4 + 2) * 5";
var ianswer = parseInt((4 + 2) * 5);
var fanswer = parseFloat((4 + 2) * 5);
var irat = parseFloat(355/113);
alert(equation+'\n'+ianswer+'\n'+fanswer+'\n'+irat);
</script>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum