使用JavaScript从字符串中删除逗号


97

我想从字符串中删除逗号并使用JavaScript计算这些金额。

例如,我有这两个值:

  • 100,000.00
  • 500,000.00

现在,我要从这些字符串中删除逗号,并希望这些金额的总和。

Answers:


172

要删除逗号,您需要replace在字符串上使用。要转换为浮点数以便可以进行数学计算,您需要parseFloat

var total = parseFloat('100,000.00'.replace(/,/g, '')) +
            parseFloat('500,000.00'.replace(/,/g, ''));

3
是的,需要结合replaceparseFloat。这是快速测试案例:jsfiddle.net/TtYpH
影子向导为您

1
是2017年,没有办法往返语言环境字符串吗?您如何反转此功能?developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/…。在这里发布了一个单独的问题:stackoverflow.com/questions/41905406/…– 2013
哥斯达黎加

4

相关答案,但是,如果您要清理将用户输入值输入表单的用户,可以执行以下操作:

const numFormatter = new Intl.NumberFormat('en-US', {
  style: "decimal",
  maximumFractionDigits: 2
})

// Good Inputs
parseFloat(numFormatter.format('1234').replace(/,/g,"")) // 1234
parseFloat(numFormatter.format('123').replace(/,/g,"")) // 123

// 3rd decimal place rounds to nearest
parseFloat(numFormatter.format('1234.233').replace(/,/g,"")); // 1234.23
parseFloat(numFormatter.format('1234.239').replace(/,/g,"")); // 1234.24

// Bad Inputs
parseFloat(numFormatter.format('1234.233a').replace(/,/g,"")); // NaN
parseFloat(numFormatter.format('$1234.23').replace(/,/g,"")); // NaN

// Edge Cases
parseFloat(numFormatter.format(true).replace(/,/g,"")) // 1
parseFloat(numFormatter.format(false).replace(/,/g,"")) // 0
parseFloat(numFormatter.format(NaN).replace(/,/g,"")) // NaN

通过使用本地国际日期format。这将清除所有错误的输入,如果有错误输入,则返回一个字符串,NaN您可以检查该字符串。当前无法删除作为区域设置一部分的逗号(截至19/12/19),因此您可以使用regex命令使用来删除逗号replace

ParseFloat 将此类型定义从字符串转换为数字

如果使用React,则您的calculate函数可能如下所示:

updateCalculationInput = (e) => {
    let value;
    value = numFormatter.format(e.target.value); // 123,456.78 - 3rd decimal rounds to nearest number as expected
    if(value === 'NaN') return; // locale returns string of NaN if fail
    value = value.replace(/,/g, ""); // remove commas
    value = parseFloat(value); // now parse to float should always be clean input

    // Do the actual math and setState calls here
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.