Skip to content

Commit

Permalink
Fix bug with invalid rounding
Browse files Browse the repository at this point in the history
  • Loading branch information
Daninet committed Aug 9, 2024
1 parent ded9756 commit cefd1e1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
24 changes: 24 additions & 0 deletions src/Fraction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,30 @@ describe('Fraction', () => {
expect(run('401.65/9').toRepeatingDigits(undefined)).toBe('44.62(7)');
});

it('ceil()', () => {
const run = (a: string, b = 1n) => new Fraction(a, b).ceil().toString();

expect(run('0')).toBe('0');
expect(run('0.99')).toBe('1');
expect(run('3.099')).toBe('4');
expect(run('3.678')).toBe('4');
expect(run('4.0000')).toBe('4');
expect(run('1234')).toBe('1234');

expect(run('-0')).toBe('0');
expect(run('-0.99')).toBe('0');
expect(run('-3.099')).toBe('-3');
expect(run('-3.678')).toBe('-3');
expect(run('-4.0000')).toBe('-4');
expect(run('-4.0001')).toBe('-4');
expect(run('-1234')).toBe('-1234');

expect(run('-1', 2n)).toBe('0');
expect(run('-3', 2n)).toBe('-1');
expect(run('-3661', 86400n)).toBe('0');
expect(run('-3661', -86400n)).toBe('1');
});

it('correct transients', () => {
const run = (a: string) => expect(new Fraction(a, 1n).toString()).toBe(a);

Expand Down
7 changes: 6 additions & 1 deletion src/Fraction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,12 @@ export class Fraction implements ExactNumberType {
// 0.105 might got cutted to 0.1, which might round incorrectly
// solution: add one digit to the end

const correctedFixedNum = new FixedNumber(`${fixedPart.toFixed(decimals + 1)}1`);
let correctedFixedNum = new FixedNumber(`${fixedPart.toFixed(decimals + 1)}1`);

// 0 loses negative sign, so it needs to be corrected
if (fixedPart.isNegative() && !correctedFixedNum.isNegative()) {
correctedFixedNum = correctedFixedNum.neg();
}

const res = correctedFixedNum.round(decimals, roundingMode);
return res;
Expand Down

0 comments on commit cefd1e1

Please sign in to comment.