Skip to content
Merged
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
13 changes: 11 additions & 2 deletions src/filesize.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,17 @@ export function filesize(
val = valueResult.result;
e = valueResult.e;

// Rounding + auto-increment ceiling
const rounded = applyRounding(val, ceil, e, round, roundingFunc, autoExponent);
// Rounding + auto-increment ceiling.
// `precision` takes precedence over `round` for decimal units (e > 0): the
// significant-digit pass below must see the un-rounded scaled value, or a
// boundary value is rounded twice (999.499 kB -> 999.5 -> "1.00e+3" -> a
// premature unit bump) and digits beyond `round` never survive to
// toPrecision(). Whole bytes (e === 0) still round to integers — a byte
// count is an integer quantity, and the sub-1-byte outputs are pinned on it.
const precisionFirst = precisionAdjusted > 0 && e > 0;
const rounded = precisionFirst
? { value: val, e }
: applyRounding(val, ceil, e, round, roundingFunc, autoExponent);
result[0] = rounded.value;
e = rounded.e;

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 @@ -337,6 +337,19 @@ describe("filesize", () => {
assert.strictEqual(filesize(1536000, { precision: 2 }), "1.5 MB");
});

it("should let precision work on the un-rounded value", () => {
// `round` used to run first, so 999.499 kB became 999.5 and
// toPrecision(3) produced "1.00e+3" — a premature unit bump — and
// digits beyond `round` were lost before toPrecision() saw them (#399).
assert.strictEqual(filesize(1245, { precision: 2 }), "1.2 kB");
assert.strictEqual(filesize(2887, { precision: 4 }), "2.887 kB");
assert.strictEqual(filesize(999499, { precision: 3 }), "999 kB");
assert.strictEqual(filesize(1245, { precision: 2, round: 0 }), "1.2 kB");
// whole bytes still round to integers
assert.strictEqual(filesize(0.001, { precision: 1 }), "0 B");
assert.strictEqual(filesize(0.5, { precision: 1 }), "1 B");
});

it("should apply locale formatting when precision is set", () => {
// A string value from toPrecision ignores toLocaleString, so the
// locale's decimal separator was previously dropped (1.2, not 1,2).
Expand Down
Loading