Skip to content

Commit

Permalink
feat: parentheses for negative amounts
Browse files Browse the repository at this point in the history
  • Loading branch information
joshcanhelp committed Nov 19, 2023
1 parent 9724001 commit 046f4ed
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
6 changes: 6 additions & 0 deletions src/utils/money.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ describe("Function: convertStringCurrencyToNumber", () => {
it("handles additional decimals", () => {
expect(convertStringCurrencyToNumber("100.011")).toEqual(100.01);
});
it("handles parentheses", () => {
expect(convertStringCurrencyToNumber("($10.33)")).toEqual(-10.33);
});
it("handles all the things at once", () => {
expect(convertStringCurrencyToNumber(" ($2,334.932) ")).toEqual(-2334.93);
});
});

describe("Function: roundCurrency", () => {
Expand Down
7 changes: 5 additions & 2 deletions src/utils/money.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
//

export const convertStringCurrencyToNumber = (amountRaw: string): number => {
amountRaw = amountRaw.trim().replaceAll("$", "").replaceAll(",", "");
const amountParsed = parseFloat(amountRaw);
let amountInProcess = amountRaw.trim().replaceAll("$", "").replaceAll(",", "");
if (amountInProcess.match(/^\(\d*\.?\d*\)$/)) {
amountInProcess = amountInProcess.replace("(", "-").replace(")", "");
}
const amountParsed = parseFloat(amountInProcess);
return roundCurrency(amountParsed);
};

Expand Down

0 comments on commit 046f4ed

Please sign in to comment.