文字列からカンマを削除し、JavaScriptを使用してそれらの量を計算します。
たとえば、次の2つの値があります。
- 100,000.00
- 500,000.00
次に、これらの文字列からコンマを削除して、それらの合計を求めます。
回答:
コンマを削除するreplace
には、文字列で使用する必要があります。計算を実行できるようにフロートに変換するには、次のものが必要ですparseFloat
。
var total = parseFloat('100,000.00'.replace(/,/g, '')) +
parseFloat('500,000.00'.replace(/,/g, ''));
関連する回答ですが、フォームに値を入力しているユーザーをクリーンアップしたい場合は、次のことができます。
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を使用する場合、計算関数は次のようになります。
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
}
replace
ありparseFloat
ます。ここに簡単なテストケースがあります:jsfiddle.net/TtYpH