Skip to content

Commit

Permalink
Fix format for integer amounts (#231)
Browse files Browse the repository at this point in the history
* support both fractions and integer values

* test fractions

* prettier
  • Loading branch information
mertd authored Sep 29, 2024
1 parent 8eea062 commit 8742bd5
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ export function CreateFromReceiptButton({
groupCurrency,
receiptInfo.amount,
locale,
true,
)}
</>
) : (
Expand Down
13 changes: 9 additions & 4 deletions src/lib/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,15 @@ describe('formatCurrency', () => {
]

for (const variation of variations) {
it(`formats ${variation.amount} in ${variation.locale}`, () => {
expect(formatCurrency(currency, variation.amount, variation.locale)).toBe(
variation.result,
)
it(`formats ${variation.amount} in ${variation.locale} without fractions`, () => {
expect(
formatCurrency(currency, variation.amount * 100, variation.locale),
).toBe(variation.result)
})
it(`formats ${variation.amount} in ${variation.locale} with fractions`, () => {
expect(
formatCurrency(currency, variation.amount, variation.locale, true),
).toBe(variation.result)
})
}
})
8 changes: 7 additions & 1 deletion src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,16 @@ export function formatCategoryForAIPrompt(category: Category) {
return `"${category.grouping}/${category.name}" (ID: ${category.id})`
}

/**
* @param fractions Financial values in this app are generally processed in cents (or equivalent).
* They are are therefore integer representations of the amount (e.g. 100 for USD 1.00).
* Set this to `true` if you need to pass a value with decimal fractions instead (e.g. 1.00 for USD 1.00).
*/
export function formatCurrency(
currency: string,
amount: number,
locale: string,
fractions?: boolean,
) {
const format = new Intl.NumberFormat(locale, {
minimumFractionDigits: 2,
Expand All @@ -40,7 +46,7 @@ export function formatCurrency(
// '€' will be placed in correct position
currency: 'EUR',
})
const formattedAmount = format.format(amount)
const formattedAmount = format.format(fractions ? amount : amount / 100)
return formattedAmount.replace('€', currency)
}

Expand Down

0 comments on commit 8742bd5

Please sign in to comment.