Search code examples
javascriptfunctioncoding-stylepercentage

Percent (%) operation on a string divided into two numbers


I am looking for help to make the following function look cleaner. I feel like I could've achieved the same thing by using less lines of code.

The title must look very confusing so let me elaborate. I've created a function that takes user input (i.e. 72+5), splits the string into two elements (72,5), converts them into numbers, calculates the percentage (72*5/100=3,6) and then adds it to the first element (72+3,6). The code outputs 75,6.

function percent() {
  x = box.value;
  var split;
  var temp;

  if (x.includes("+")) {
    split = x.split("+");
    temp = Number(split[0]) * Number(split[1]) / 100;
    box.value = Number(split[0]) + temp;
  }

Solution

  • Your code is actually quite fine, it could be imroved by using the unary plus operator and array destructuring:

    const input = box.value;
    if(input.includes("+")) {
      const [a, b] = input.split("+");
      box.value = (+a * +b) / 100 + +a;
    }