Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/fix-uscurrency-thousands-separators.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion src/scalars/USCurrency.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
16 changes: 16 additions & 0 deletions tests/USCurrency.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) => {
Expand Down