How to Make Your Own Online Calculator


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:

  • Use PHP, HTML, CSS and javascript only
  • 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 just 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.

To solve the “no refreshing the page” you have to use Ajax. Ajax is a quite popular method to add content to a page that is already loaded. I would recommend you to use the javascript library jQuery to send ajax-requests and to handle the response. The response data should be written on the page in a way that you can see result history. Thanks to jQuery there is only need for a couple of hundreds line of javascript and the code is not messy at all. jQuery can do a lot more than sending HTTP-requests. You can animate DOM elements, add event listeners, manipulate with CSS etc.

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.


Leave a Reply