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

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

例如,我有这两个值:

  • 100.000.00
  • 500.000.00

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

204811 次浏览

要删除逗号,需要对字符串使用 replace。要转换成浮点数,你需要 parseFloat:

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

Related answer, but if you want to run clean up a user inputting values into a form, here's what you can do:

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字符串,您可以对其进行检查。目前还没有办法将逗号作为区域设置 (截至1919年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
}

To remove commas, you will need to use string replace method.

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");