From cbd5a990ad828ba3705ba3f2e4b20561e2c6a365 Mon Sep 17 00:00:00 2001 From: naveentehrpariya Date: Mon, 24 Aug 2026 11:19:38 +0530 Subject: [PATCH] fix: keep precision trailing zeros for negative values The precision option leaves the value as a string from toPrecision (e.g. "1.50"), but decorateResult negated it arithmetically, coercing it back to a number and dropping the requested trailing zeros: filesize(1500, {precision: 3}) // '1.50 kB' filesize(-1500, {precision: 3}) // '-1.5 kB' <- precision lost Prefix the sign for the string case instead, so a negative value keeps the same significant digits as its positive counterpart. --- src/helpers.js | 5 ++++- tests/unit/filesize.test.js | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/helpers.js b/src/helpers.js index 7358771..e4f1c73 100644 --- a/src/helpers.js +++ b/src/helpers.js @@ -403,7 +403,10 @@ export function decorateResult( roundingFunc, ) { if (neg) { - result[0] = -result[0]; + // `precision` leaves the value as a string from toPrecision (e.g. "1.50"). + // Negating that arithmetically coerces it back to a number and drops the + // trailing zeros the option asked for, so prefix the sign instead. + result[0] = typeof result[0] === "string" ? `-${result[0]}` : -result[0]; } if (symbols[result[1]]) { diff --git a/tests/unit/filesize.test.js b/tests/unit/filesize.test.js index 4cb51cf..9434777 100644 --- a/tests/unit/filesize.test.js +++ b/tests/unit/filesize.test.js @@ -394,6 +394,16 @@ describe("filesize", () => { assert.strictEqual(filesize(-1234567890, { precision: 2 }), "-1.2 GB"); }); + it("should keep precision trailing zeros for negative values", () => { + // A negative value must carry the same significant digits as its positive counterpart + assert.strictEqual(filesize(1500, { precision: 3 }), "1.50 kB"); + assert.strictEqual(filesize(-1500, { precision: 3 }), "-1.50 kB"); + assert.strictEqual(filesize(-1000, { precision: 3 }), "-1.00 kB"); + assert.strictEqual(filesize(-1, { precision: 3 }), "-1.00 B"); + assert.deepStrictEqual(filesize(-1500, { precision: 3, output: "array" }), ["-1.50", "kB"]); + assert.strictEqual(filesize(-1500, { precision: 3, output: "object" }).value, "-1.50"); + }); + it("should ensure no scientific notation in any precision result", () => { // Test a range of numbers that would normally produce scientific notation from toPrecision // but should have it removed by our implementation