From 68f39be022d2d4cfe519059018e29f8b48cfa311 Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Thu, 26 Nov 2026 06:05:31 +0530 Subject: [PATCH] fix: keep exact BigInt values exact with floor and ceil rounding --- src/helpers.js | 20 +++++++++++++++----- tests/unit/filesize.test.js | 13 +++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/helpers.js b/src/helpers.js index 89b24bb..379f341 100644 --- a/src/helpers.js +++ b/src/helpers.js @@ -241,11 +241,21 @@ export function calculateBigIntExponent(num, e, exponent, isDecimal, precision) */ export function calculateBigIntValue(num, e, isDecimal, bits, ceil, autoExponent = true) { const power = isDecimal ? 10n ** BigInt(3 * e) : 1024n ** BigInt(e); - // Scaled division preserves precision above Number.MAX_SAFE_INTEGER. - // Multiply by 10^16 before dividing, then scale back down, so the - // quotient keeps ~16 significant digits instead of collapsing to a float. - const SHIFT = 10n ** 16n; - let result = Number((num * SHIFT) / power) / Number(SHIFT); + const n = Number(num); + const d = Number(power); + let result; + if (BigInt(n) === num && BigInt(d) === power) { + // Both values are exact numbers, so one division gives the correctly + // rounded quotient (the same value as the number path). The scaled + // division below rounds twice and turns 59033 into 59032.99999999999. + result = n / d; + } else { + // Scaled division preserves precision above Number.MAX_SAFE_INTEGER. + // Multiply by 10^16 before dividing, then scale back down, so the + // quotient keeps ~16 significant digits instead of collapsing to a float. + const SHIFT = 10n ** 16n; + result = Number((num * SHIFT) / power) / Number(SHIFT); + } if (bits) { result *= 8; diff --git a/tests/unit/filesize.test.js b/tests/unit/filesize.test.js index 73e3390..3ddb99b 100644 --- a/tests/unit/filesize.test.js +++ b/tests/unit/filesize.test.js @@ -1161,6 +1161,19 @@ describe("filesize", () => { assert.strictEqual(objectResult.value, 1.02); assert.strictEqual(objectResult.symbol, "kB"); }); + + it("should keep an exact whole value with floor and ceil rounding", () => { + assert.strictEqual(filesize(59033n, { exponent: 0, roundingMethod: "floor" }), "59033 B"); + assert.strictEqual(filesize(59031n, { exponent: 0, roundingMethod: "ceil" }), "59031 B"); + assert.strictEqual( + filesize(76745800n, { exponent: 1, roundingMethod: "floor" }), + "76745.8 kB", + ); + assert.strictEqual( + filesize(246770688n, { base: 2, exponent: 1, roundingMethod: "floor" }), + "240987 KiB", + ); + }); }); describe("partial() with BigInt input", () => {