解析浮点数和toFixed()

3

我的代码已经可以正常运行,但是我想添加parseFloat选项和'toFixed()'将结果保留两位小数。我不确定这两行代码应该放在哪里。我创建了一个单位转换网站,可以将用户输入的英寸数转换为英尺。

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <center><title>Unit Coversion Table</title><center>
</head>
<body>

<div id="question">
  <h2>Unit Convertor</h2>
  <p>Enter a Quanity of Inches: <input id="userinches" type="number" /> </p>
</div>  <!-- End of question div section -->

<div id="conversion">
  <script>
    function feet() {
      var userinches = document.getElementById('userinches').value;
      doOuput('The answer is ', userinches * 0.0833);
    }

    function doOuput(val, unit) {
      document.getElementById('results').innerHTML = val + unit;
    }
  </script>
</div>  <!-- End of conversion div section -->

<div="buttons">
  <button type="button" id="buttonft" onclick="feet();">Feet</button>
</div> <!-- End of buttons div section -->

<div id="results"></div>  <!-- End of results div section -->

</body>
</html>
2个回答

5

你可以在feet()函数中添加它,其中你获取输入值并将其转换为英尺:

function feet() {
  var userinches = document.getElementById('userinches').value;
  var feetValue = parseFloat(userinches * 0.0833).toFixed(2);
  doOuput('The answer is ', feetValue);
}

0

您可以通过以下两种方式之一实现:

  1. 在调用函数doOutput()时将值传递给feet()。
  2. 在doOutput()函数中实现。

工作示例 https://codepen.io/Ashish9342/pen/YOOawR

//On key up enter or pressing enter
function checkForEnter() {
  var input = document.getElementById("userinches");
  input.addEventListener("keyup", function(event) {
    event.preventDefault();
    //check if input has a greater than zero
    if (input.value.length > 0 && event.keyCode === 13) {
      document.getElementById("buttonft").click();
    }
  });
}
checkForEnter();



// converting the value to feet in 2 fixed decimal
function feet() {
  var userinches = document.getElementById('userinches').value;
  doOuput('The answer is ', userinches * 0.0833).toFixed(2);
  //doOuput('The answer is ', userinches * 0.0833);

}

function doOuput(val, unit) {
  document.getElementById('results').innerHTML = val + unit;
  //document.getElementById('results').innerHTML = val + unit.toFixed(2);
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接