diff --git a/src/filesize.js b/src/filesize.js index 1977b11..12c54f4 100644 --- a/src/filesize.js +++ b/src/filesize.js @@ -126,10 +126,6 @@ export function filesize( e = calculatedE; const autoExponent = exponent === -1 || isNaN(exponent); - if (output === EXPONENT) { - return e; - } - const { result: valueResult, e: valueExponent } = calculateOptimizedValue( num, e, @@ -164,6 +160,13 @@ export function filesize( e = precisionResult.e; } + // Return the exponent only after every adjustment that other output + // modes apply (bits auto-increment, rounding overflow, precision), so + // it always matches the exponent reported by object output. + if (output === EXPONENT) { + return e; + } + u = resolveSymbol(actualStandard, bits, e, isDecimal); result[1] = u; diff --git a/tests/unit/filesize.test.js b/tests/unit/filesize.test.js index 3e8ac6c..fa6a469 100644 --- a/tests/unit/filesize.test.js +++ b/tests/unit/filesize.test.js @@ -128,6 +128,26 @@ describe("filesize", () => { assert.strictEqual(typeof result, "number"); assert.strictEqual(result, 1); }); + + it("should match the object exponent when rounding overflows the unit", () => { + // 999999 renders as "1 MB", so the exponent is 2, not 1 + assert.strictEqual(filesize(999999, { output: "exponent" }), 2); + assert.strictEqual( + filesize(999999, { output: "exponent" }), + filesize(999999, { output: "object" }).exponent, + ); + // IEC: 1048575 renders as "1 MiB" + assert.strictEqual(filesize(1048575, { standard: "iec", output: "exponent" }), 2); + }); + + it("should match the object exponent when bits auto-increment the unit", () => { + // 125000 bytes = 1 Mbit, so the exponent is 2, not 1 + assert.strictEqual(filesize(125000, { bits: true, output: "exponent" }), 2); + assert.strictEqual( + filesize(125000, { bits: true, output: "exponent" }), + filesize(125000, { bits: true, output: "object" }).exponent, + ); + }); }); describe("Rounding", () => {