I recently made my own calculator and was surprised at how difficult it was. Yes, of course, a simple calculator that supports the basics is not very difficult to make. online vat calculatorBut I had the following specification:
-Use only PHP, HTML, CSS and Javascript
-An input field
-result history
-No page refresh
-Support for 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 have to separate them later for the calculations. That's a lot easier said than done. For example, how do you determine the different meaning of the substring "-3" in " sqrt ( 6-3+5)" and " sqrt (-3+5)"? The answer is regular expressions.
When developing your calculator, you need to use a lot of regex to separate numbers, operators, and functions. For example, take this string: "3+4.2-1". You need to break it down into 3 parts and know which parts are operators and which parts are numbers. When that's done, all you have to do is evaluate the expressions in the correct mathematical order, put the results together, and re-evaluate the parts until there's only one part left and (hopefully) your answer. The advanced arithmetic tasks like pi, square root, trigonometric function etc. are solved with built-in PHP functions.
To solve the page not refreshing issue, you need to use Ajax. Ajax is quite a popular way to add content to an already loaded page. I would recommend you to use javascript library jQuery to send ajax requests and handle the response. The response data should be written on the page in such a way that you can see the history of the results. Thanks to jQuery, you only need a few hundred lines of javascript and the code isn't messy at all. jQuery can do much more than just send HTTP requests. You can animate DOM elements, add event listeners, manipulate with CSS, etc.
By | Feroz Ali |
Added | Oct 18 '22 |
The Wall