【问题标题】:Simple multiplication calculator not retaining decimal value简单的乘法计算器不保留十进制值
【发布时间】:2018-08-24 07:04:15
【问题描述】:

这是一个简单的乘法计算器,在键入时会自动将逗号添加到单独的数千组中。但是它不接受十进制值,例如 1,778.23。直接复制粘贴到字段中可以,但不能输入。任何解决方案将不胜感激。

function calculate() {
  var myBox1 = updateValue('box1');
  var myBox2 = updateValue('box2');
  var myResult = myBox1 * myBox2;
  adTextRes('result', myResult)
}

function updateValue(nameOf) {
  var inputNo = document.getElementById(nameOf).value;
  var no = createNo(inputNo);
  adTextRes(nameOf, no);
  return no;
}

function adTextRes(nameOf, no) {
  var asText = String(no).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  document.getElementById(nameOf).value = asText;
}

function createNo(textin) {
  return Number(textin.replace(/,/g, ""));
}
<table width="80%" border="0">
  <tr>
    <th>Box 1</th>
    <th>Box 2</th>
    <th>Result</th>
  </tr>
  <tr>
    <td><input id="box1" type="text" oninput="calculate()" /></td>
    <td><input id="box2" type="text" oninput="calculate()" /></td>
    <td><input id="result" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>

【问题讨论】:

    标签: javascript html converter calculator multiplication


    【解决方案1】:

    问题是,在createNo:

    return Number(textin.replace(/,/g, ""));
    

    转换为Number 时,尾随句点将被丢弃。不过,一开始就不需要这样的演员表——只要把它关掉,它就会按预期工作:

    function createNo(textin) {
      return textin.replace(/,/g, "");
    }
    

    为防止输入多个小数点,您可以在同一函数中使用另一个replace

    .replace(/(\.\d*)\./, '$1')
    

    function calculate() {
      var myBox1 = updateValue('box1');
      var myBox2 = updateValue('box2');
      var myResult = myBox1 * myBox2;
      adTextRes('result', myResult)
    }
    
    function updateValue(nameOf) {
      var inputNo = document.getElementById(nameOf).value;
      var no = createNo(inputNo);
      adTextRes(nameOf, no);
      return no;
    }
    
    function adTextRes(nameOf, no) {
      var asText = String(no).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      document.getElementById(nameOf).value = asText;
    }
    
    function createNo(textin) {
      return textin
        .replace(/,/g, "")
        .replace(/(\.\d*)\./, '$1')
    }
    <table width="80%" border="0">
      <tr>
        <th>Box 1</th>
        <th>Box 2</th>
        <th>Result</th>
      </tr>
      <tr>
        <td><input id="box1" type="text" oninput="calculate()" /></td>
        <td><input id="box2" type="text" oninput="calculate()" /></td>
        <td><input id="result" /></td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
    </table>

    【讨论】:

    • 可能还有改进的余地,这段代码接受多个小数点...
    • 谢谢。这就是我要找的。​​span>
    猜你喜欢
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    相关资源
    最近更新 更多