| 2022-03-26

Make a ReactJS Calculator

    This calculator project was designed in React.

    Coding a JavaScript Calculator is fairly straightforward. The approach that I used was to build and evaluate a ‘formula’ expression string, based on user input. For example, the formula 1 + 1 will output 2. This functionality is built into JavaScript.

      const handleCalculate = () => {
        return eval(formula);
      };
      //output: 2
    
    JavaScript

    The challenge is organizing the input into a formula for evaluation, and for display. For example, these functions test for operators, or decimal places, and adds commas to whole numbers appropriately for thousand places.

       const formulaArray = formula.split(",");
       const withCommas = formulaArray.map((item) => {
         if (isOp(item)) {
           return item;
         } else if (hasDecimal(item)) {
           const itemArray = item.split(".");
           const firstItem = itemArray[0];
           const secondItem = itemArray[1];
           const firstItemWithCommas = numberWithCommas(firstItem);
           return firstItemWithCommas + "." + secondItem;
         } else {
           return numberWithCommas(item);
         }
       });
    
    JavaScript

    Here above, we test the formula, and filter out the operators. Then we separate the numbers on the left side of a decimal point from numbers on the right. Then we give numbers on the left side commas at thousand places – for display. If there is no decimal place, the number is simply given commas if needed.

      function numberWithCommas(x) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      }
    
    JavaScript

    The code above uses a regular expression to add commas in the appropriate thousands place. Learn more about this code here.

    const isOp = (item) => {
        if (item === "+" || item === "-" || item === "*" || item === "/") {
        return true;
        } else {
        return false;
        }
    };
    
    JavaScript

    The code above determines if the item is an operator or not.

       const hasDecimal = (item) => {
        if (item.includes(".")) {
          return true;
        } else {
          return false;
        }
      };
    
    JavaScript

    The code above checks whether the item is a number with a decimal place.

    Find the ReactJS code for the JavaScript Calculator app here.


    Thanks for reading. If you enjoyed this post, I invite you to explore more of my site. I write about web development, programming, and other fun stuff.