Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
13 changes: 13 additions & 0 deletions tests/unit/filesize.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
Loading