diff --git a/.changeset/fix-uscurrency-thousands-separators.md b/.changeset/fix-uscurrency-thousands-separators.md new file mode 100644 index 000000000..adf6be0ca --- /dev/null +++ b/.changeset/fix-uscurrency-thousands-separators.md @@ -0,0 +1,9 @@ +--- +'graphql-scalars': patch +--- + +Fix `USCurrency` parsing of amounts with more than one thousands separator + +`generateCents` stripped only the first comma, so a value like `$1,000,000.00` parsed to the wrong +amount (`parseFloat` stopped at the second separator, yielding `$1,000.00`). It now removes every +separator. diff --git a/src/scalars/USCurrency.ts b/src/scalars/USCurrency.ts index 014ec767d..7012012be 100644 --- a/src/scalars/USCurrency.ts +++ b/src/scalars/USCurrency.ts @@ -16,7 +16,7 @@ function generateCurrency(value: any) { } function generateCents(value: string) { - const digits = value.replace('$', '').replace(',', ''); + const digits = value.replace('$', '').replace(/,/g, ''); const number = parseFloat(digits); return number * 100; } diff --git a/tests/USCurrency.test.ts b/tests/USCurrency.test.ts index 6ae96d24b..db946057b 100644 --- a/tests/USCurrency.test.ts +++ b/tests/USCurrency.test.ts @@ -147,6 +147,22 @@ describe('USCurrency', () => { }); }); + it('should parse literal value with multiple thousands separators', () => { + const value = '$1,000,000.00'; + const schema = createGraphQLSchema(noop, (source, { currencyValue }) => { + expect(currencyValue).toEqual(100000000); + return currencyValue; + }); + const source = /* GraphQL */ ` + mutation { + setCurrency(currencyValue:"${value}") + } + `; + return graphql({ schema, source }).then(result => { + expect(result.errors).toBeFalsy(); + }); + }); + it('should parse input string value', () => { const value = '$12.50'; const schema = createGraphQLSchema(noop, (source, { currencyValue }) => {