I recently made my own calculator and I was surprised how difficult it was. Yes of course a simple calculator that supports the basics is not very hard to do. But I had the following specification:
- One input field
- Result history
- No refreshing the page
- Support trigonometric functions
- Support for Pi, Sqrt and logarithm
The real challenge is the "one input field" -thing. If you let the user write numbers and operators in the same input field you will have to separate them from each other later to perform the calculations. That is much easier said that done. For example, how do you determine the different meanings of the substring "-3" in "sqrt (6-3 + 5)" and "sqrt (-3 + 5)"? The answer is regular expressions.
When you develop your calculator you have to use a lot of regex to separate numbers, operators and functions form each other. Take this string for example: "3 + 4.2-1". You have to break it into 3 parts and you have to know which pars that is operators and which parts that is numbers. When this is done you just have to evaluate the expressions in the correct mathematical order, put the results together and evaluate the parts again until there is only one part left and (hopefully) there is your answer. The advanced calculator stuff like Pi, square root, trigonometric function etc is solved with built in PHP functions.
When you are writing a program or anything that will be used by others than yourself you have to write test code. A lot of test code. You will need approximately 50+ different expressions to test if your calculator calculates them correctly. You will probably fail a lot of times before you pass them all.
When the functionality is finished you need to add some design, some instructions and the calculator is ready to be used.