首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用JavaScript删除字符串中的逗号

使用JavaScript删除字符串中的逗号
EN

Stack Overflow用户
提问于 2011-04-26 18:03:08
回答 3查看 171.1K关注 0票数 115

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

例如,我有这两个值:

  • 100,000.00
  • 500,000.00

现在我想要从这些字符串中删除逗号,并想要这些数量的总和。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-04-26 18:07:47

要删除逗号,需要对字符串使用replace。要转换为浮点型以便进行数学运算,您将需要parseFloat

代码语言:javascript
复制
var total = parseFloat('100,000.00'.replace(/,/g, '')) +
            parseFloat('500,000.00'.replace(/,/g, ''));
票数 206
EN

Stack Overflow用户

发布于 2019-10-17 03:21:31

相关答案,但如果您希望运行clean用户在表单中输入值,则可以执行以下操作:

代码语言:javascript
复制
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字符串。目前还不能将逗号作为区域设置的一部分删除(从10/12/19开始),因此您可以使用正则表达式命令通过replace删除逗号。

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

如果使用React,则计算函数可能如下所示:

代码语言:javascript
复制
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
}
票数 5
EN

Stack Overflow用户

发布于 2020-11-25 18:01:44

这是最简单的方法。

代码语言:javascript
复制
let total = parseInt(('100,000.00'.replace(',',''))) + parseInt(('500,000.00'.replace(',','')))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5788741

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档