javascript - 简单的乘法计算器不保留小数值

标签 javascript html converters calculator multiplication

这是一个简单的乘法计算器,输入时会自动将逗号添加到单独的千组中。但是它不接受十进制值,例如 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>

最佳答案

问题是,在createNo中:

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

当转换为数字时,尾随句点将被丢弃。不过,一开始就没有必要进行这样的转换 - 只需将其保留,它就会按预期工作:

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>

关于javascript - 简单的乘法计算器不保留小数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51999122/

相关文章:

java - 长字符串转为十六进制字符串

c# - 对象到字节数组到字符串并返回

javascript - 即使已解决,Promise 也会挂起

javascript - 如何在ace编辑器中显示html站点的代码

javascript - 圆不会在 Canvas 上绘制

php - FPDF错误: Unsupported image type: image/jpeg

c# - WPF DataGrid 中选定行的前景色未更新

javascript - 使用 React 构建一个安静的 Web 应用程序并具有多个角色

php - 上传多个文件的最佳策略

javascript - 编辑存储在服务器上的文本文件