OWolf

2024-09-09 web, development, javascript

Make a ReactJS Calculator

By O. Wolfson

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.

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

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.

JavaScript
   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);
     }
   });

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.

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

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

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

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

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

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

Find the ReactJS code for the JavaScript Calculator app here.