将逗号添加到数字后执行计算

时间:2018-11-08 20:58:36

标签: javascript

我有以下功能,可在文本字段中添加逗号。示例:5000000返回为5,000,000

function addComma(values) {
   values.value = values.value.replace(",", "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

if (document.getElementById("values"))
    payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">

但是,我不能再将其与其他变量一起使用。如果我删除parseInt,它将返回NAN,添加parseInt将返回5

payment = 10;
values = 5,000,000

以下内容在调试时返回PV = payment * NAN5,000,000

PV = payment*values;

我在这里做错了什么?任何帮助表示赞赏。谢谢!

3 个答案:

答案 0 :(得分:1)

您可以使用以下命令删除逗号:

values = values.replace(/\,/g,'')

这实质上删除了字符串中的所有逗号 现在,使用以下命令将有效表示一个数字的字符串转换为确实是一个数字:

values = Number(values)

希望有帮助!

答案 1 :(得分:1)

您正在尝试对添加了逗号的字符串使用parseIntparseInt将在第一个非数字字符之后停止解析:

  

如果parseInt遇到的字符不是指定基数中的数字,则它将忽略该字符以及所有后续字符,并返回到该点为止已解析的整数值。 parseInt将数字截断为整数值。允许使用前导和尾随空格。

console.log(parseInt('123456')); // 123456
console.log(parseInt('123,456')); // 123

鉴于此,您应在分析之前删除逗号:

function addComma(values) {
  values.value = values.value.replace(",", "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  
  // Moved the rest of the conde into the function so you can
  // see the output as you type.
  // Get your element by Id into a const so you don't need to query twice.
  const element = document.getElementById("values");
  if (element) {
    // Remove commas from the number to be parsed
    const value = element.value.replace(",", "");
    // It is best practice to include the radix when calling parseInt
    const payment = parseInt(value, 10);
    console.log(payment);
  }
}
<label>Rent</label> <input id="values" type="text" onkeyup="addComma(this);">

答案 2 :(得分:0)

执行以下操作对我有用。

payment = document.getElementById("values").value;
var Return = payment.replace(/\,/g,'');

我没有声明parseInt而是声明了另一个变量并删除逗号以执行任何进一步的计算。