diff --git a/src/Fraction.test.ts b/src/Fraction.test.ts index b856db5..028a79e 100644 --- a/src/Fraction.test.ts +++ b/src/Fraction.test.ts @@ -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); diff --git a/src/Fraction.ts b/src/Fraction.ts index 510364d..59fc7e1 100644 --- a/src/Fraction.ts +++ b/src/Fraction.ts @@ -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;