Skip to content

Commit

Permalink
fix: precision ceil for negative numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
fahyik yong authored and fahyik committed Jul 22, 2020
1 parent 5d5c3a6 commit 9b5bc43
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
9 changes: 9 additions & 0 deletions src/__tests__/precision.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,15 @@ describe('unsafeSetPrecision()', () => {
precision: 1,
});
});
it('returns a monetary value (negative) with a matching amount up to the relevant digit when provided a lower precision', () => {
expect(
unsafeSetPrecision({ amount: -314, currency: 'EUR', precision: 2 }, 1),
).toBeIdenticalToMonetaryValue({
amount: -31,
currency: 'EUR',
precision: 1,
});
});
it('returns a monetary value with a matching amount up to the relevant digit, rounded according to the provided rounding function, when provided a lower precision', () => {
expect(
unsafeSetPrecision(
Expand Down
5 changes: 4 additions & 1 deletion src/precision.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,10 @@ export function unsafeSetPrecision<C extends string>(
): MonetaryValue<C> {
if (monetaryValue.precision >= precision) {
const divider = pow10(monetaryValue.precision - precision);
const wholePart = Math.floor(monetaryValue.amount / divider);
const wholePart =
monetaryValue.amount < 0
? Math.ceil(monetaryValue.amount / divider)
: Math.floor(monetaryValue.amount / divider);
const numerator = monetaryValue.amount % divider;
return {
amount: roundingFunction(wholePart, numerator, divider),
Expand Down

0 comments on commit 9b5bc43

Please sign in to comment.