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

126

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

例如,我有以下两个值:

  • 100,000.00
  • 500,000.00

现在我想要从这些字符串中删除逗号,并计算这些金额的总数。


1
虽然不是很高效,但你可以使用 "1,000,000.00".split(',").join("") - Shelby115
3个回答

234
为了移除逗号,你需要在字符串上使用 replace。为了将其转换为浮点数以便进行计算,你需要使用parseFloat
var total = parseFloat('100,000.00'.replace(/,/g, '')) +
            parseFloat('500,000.00'.replace(/,/g, ''));

3
需要结合replaceparseFloat。这是一个快速测试案例:http://jsfiddle.net/TtYpH/ - Shadow The Spring Wizard
1
现在已经是2017年了,有没有办法将本地字符串转换为数字并且反过来呢?如何反转这个函数?https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString。我在这里发布了一个单独的问题:https://dev59.com/gZ7ha4cB1Zd3GeqPl5_-#41905454 - Costa Michailidis

6

有关答案,但如果您想清理用户在表单中输入的值,可以执行以下操作:

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字符串以供您检查。目前还没有一种方法可以删除逗号以作为本地语言的一部分(截至2019年10月12日),因此您可以使用正则表达式命令使用replace来移除逗号。

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

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

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

要去掉逗号,你需要使用字符串替换方法。

var numberArray = ["1000,00", "23", "11"];

//If String
var arrayValue = parseFloat(numberArray.toString().replace(/,/g, ""));

console.log(arrayValue, "Array into toString")

// If Array

var number = "23,949,333";
var stringValue = parseFloat(number.replace(/,/g, ""));

console.log(stringValue, "using String");


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接