Javascript计算器应用中的前导零和十进制

时间:2018-08-17 05:22:22

标签: javascript decimal zero calculation

我为锻炼目的构建了一个简单的计算器应用程序。但是,我遇到了一些错误,例如:

  1. 如果没有小数点,则不应有前导零。 (即023应该是23)
  2. 如果数字小于1且大于零,则应显示前导零。 (即.21应该为0.21)
  3. 数字中最多允许小数点后一位。 (即0.9 ...应仅为0.9)

以下是codepen中的源代码:this.link

JS中的源代码:

// Variables
  var viewer = el("#viewer"), // Calculator screen where result is displayed
    equals = el("#equals"), // Equal button
    nums = el(".num"), // List of numbers
    ops = el(".ops"), // List of operators
    theNum = "", // Current number
    oldNum = "", // First number
    resultNum, // Result
    operator; // Batman

  // When: Number is clicked. Get the current number selected
  var setNum = function() {

    if (resultNum) { // If a result was displayed, reset number
      theNum = this.getAttribute("data-num");
      resultNum = "";
    } else { // Otherwise, add digit to previous number (this is a string!)
      theNum += this.getAttribute("data-num");
    }

    viewer.innerHTML = theNum; // Display current number

  };

  // When: Operator is clicked. Pass number to oldNum and save operator
  var moveNum = function() {
    oldNum = theNum;
    theNum = "";
    operator = this.getAttribute("data-ops");


    equals.setAttribute("data-result", ""); // Reset result in attr
  };

  // When: Equals is clicked. Calculate result
  var displayNum = function() {

    // Convert string input to numbers
    oldNum = parseFloat(oldNum);
    theNum = parseFloat(theNum);

    // Perform operation
    switch (operator) {
      case "plus":
        resultNum = oldNum + theNum;
        break;

      case "minus":
        resultNum = oldNum - theNum;
        break;

      case "times":
        resultNum = oldNum * theNum;
        break;

      case "divided by":
        resultNum = oldNum / theNum;
        break;

        // If equal is pressed without an operator, keep number and continue
      default:
        resultNum = theNum;
    }

    // If NaN or Infinity returned
    if (!isFinite(resultNum)) {
      if (isNaN(resultNum)) { // If result is not a number; set off by, eg, double-clicking operators
        resultNum = "You broke it!";
      } else { // If result is infinity, set off by dividing by zero
        resultNum = "Look at what you've done";
        el('#calculator').classList.add("broken"); // Break calculator
        el('#reset').classList.add("show"); // And show reset button
      }
    }

    // Display result, finally!
    viewer.innerHTML = resultNum;
    equals.setAttribute("data-result", resultNum);

    // Now reset oldNum & keep result
    oldNum = 0;
    theNum = resultNum;

  };

  // When: Clear button is pressed. Clear everything
  var clearAll = function() {
    oldNum = "";
    theNum = "";
    viewer.innerHTML = "0";
    equals.setAttribute("data-result", resultNum);
  };

  /* The click events */

  // Add click event to numbers
  for (var i = 0, l = nums.length; i < l; i++) { //
    nums[i].onclick = setNum;
  }

  // Add click event to operators
  for (var i = 0, l = ops.length; i < l; i++) {
    ops[i].onclick = moveNum;
  }

  // Add click event to equal sign
  equals.onclick = displayNum;

  // Add click event to clear button
  el("#clear").onclick = clearAll;

  // Add click event to reset button
  el("#reset").onclick = function() {
    window.location = window.location;
  };

任何人都可以对解决方案提出建议吗?预先感谢!

1 个答案:

答案 0 :(得分:3)

您可以使用JavaScript的parseFloattoFixed函数。使用parseFloat将字符串转换为float并检查它是整数还是有理数。使用toFixed可以将数字转换为带小数点的0(如果是整数)或带小数点(如果有理)的字符串。 totoxed将负责删除前导零,并为0到1之间的数字附加前导零。

您可以使用以下示例:

var processNumString = function (str) {
  var floatNum = parseFloat(str);
  var res = floatNum % 1 == 0 ? floatNum.toFixed(0) : floatNum.toFixed(1);
  return res;
}

以下是带有某些示例用法的函数

var processNumString = function (str) {
    var floatNum = parseFloat(str);
    var res = floatNum % 1 == 0 ? floatNum.toFixed(0) : floatNum.toFixed(1);
    return res;
}

console.log(processNumString("22"));
console.log(processNumString("0022"));
console.log(processNumString("22.25"));
console.log(processNumString(".25"));