JavaScriptを使用して文字列からカンマを削除します


94

文字列からカンマを削除し、JavaScriptを使用してそれらの量を計算します。

たとえば、次の2つの値があります。

  • 100,000.00
  • 500,000.00

次に、これらの文字列からコンマを削除して、それらの合計を求めます。

回答:


169

コンマを削除するreplaceには、文字列で使用する必要があります。計算を実行できるようにフロートに変換するには、次のものが必要ですparseFloat

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

3
うん、と組み合わせる必要がreplaceありparseFloatます。ここに簡単なテストケースがあります:jsfiddle.net/TtYpH
Shadow Wizard is Ear For You

1
それは2017年だ、とに行くための方法はありませんから、ロケール文字列は?この機能をどのように元に戻しますか?developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。別の質問をここに投稿しました:stackoverflow.com/questions/41905406/…–
コスタ

3

関連する回答ですが、フォームに値を入力しているユーザーをクリーンアップしたい場合は、次のことができます。

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
}
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.