Skip to content

Commit

Permalink
fix: rounding errors for negative values in misc
Browse files Browse the repository at this point in the history
  • Loading branch information
Timothy Brookes authored and MrShiny608 committed Jun 14, 2022
1 parent d3a3f0a commit 984a2b1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
25 changes: 21 additions & 4 deletions src/operations/__tests__/misc.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { sum, pow10, allocate as numberAllocate } from '../../utils/math';
import { unsafeAdd } from '../binary';
import { negate } from '../unary';

import {
integerDivide,
Expand All @@ -11,7 +12,7 @@ import {
allocate,
unsafeAllocate,
} from '../misc';
import { roundTowardsZero } from '../../roundings';
import { roundHalfToEven, roundTowardsZero } from '../../roundings';

describe('multiply()', () => {
it('returns the same monetary value as unsafeMultiply()', () => {
Expand Down Expand Up @@ -138,7 +139,7 @@ describe('unsafeMultiply()', () => {
unsafeMultiply(mv, factor, factorPrecision, roundTowardsZero),
).toHaveProperty(
'amount',
Math.floor((mv.amount * factor) / pow10(factorPrecision)),
Math.trunc((mv.amount * factor) / pow10(factorPrecision)),
);
},
),
Expand Down Expand Up @@ -280,10 +281,26 @@ describe('unsafeIntegerDivide()', () => {
fc.pre(divider !== 0);
expect(
unsafeIntegerDivide(mv, divider, roundTowardsZero),
).toHaveProperty('amount', Math.floor(mv.amount / divider));
).toHaveProperty('amount', Math.trunc(mv.amount / divider));
}),
);
});
it('returns the same absolute monetary value when working with negative and positive values', () => {
fc.assert(
fc.property(
fc.monetaryValue(),
fc.integer(),
(mv, divider) => {
fc.pre(divider !== 0);
expect(
Math.abs(unsafeIntegerDivide(mv, divider, roundHalfToEven).amount),
).toEqual(
Math.abs(unsafeIntegerDivide(negate(mv), divider, roundHalfToEven).amount),
)
},
),
);
});
});

describe('divide()', () => {
Expand Down Expand Up @@ -451,7 +468,7 @@ describe('unsafeDivide()', () => {
unsafeDivide(mv, divider, dividerPrecision, roundTowardsZero),
).toHaveProperty(
'amount',
Math.floor((mv.amount * pow10(dividerPrecision)) / divider),
Math.trunc((mv.amount * pow10(dividerPrecision)) / divider),
);
},
),
Expand Down
2 changes: 1 addition & 1 deletion src/operations/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export function unsafeIntegerDivide<C extends string>(
divider: number,
roundingFunction: RoundingFunction = roundHalfToEven,
): MonetaryValue<C> {
const wholePart = Math.floor(monetaryValue.amount / divider);
const wholePart = Math.trunc(monetaryValue.amount / divider);
const numerator = monetaryValue.amount % divider;
return {
amount: roundingFunction(wholePart, numerator, divider),
Expand Down

0 comments on commit 984a2b1

Please sign in to comment.