具有千位分隔符的简单乘法计算器

时间:2018-08-19 11:47:41

标签: javascript html converter currency multiplication

这是一个简单的乘法计算器,将框1的值x框2的值相乘并得出结果。我要实现的是,所有三个框都应添加千位分隔符,同时保留小数部分。

如果我在框1或2中输入1000,则应自动转换为1000

例如:1232323 x 23应该是1,232,323 x 23 = 28,343,429

	function calculate() {
		var myBox1 = document.getElementById('box1').value;	
		var myBox2 = document.getElementById('box2').value;
		var result = document.getElementById('result');	
		var myResult = myBox1 * myBox2;
		result.value = myResult;
      }
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  
<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>
  
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容作为答案。

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>