From 7b781162acb72dac112a365156dae374491edcbd Mon Sep 17 00:00:00 2001 From: DualFroz Date: Fri, 4 Sep 2026 04:49:30 +0200 Subject: [PATCH] fix(helpers): keep fullform singular for negative one-magnitude values decorateResult() captured numericValue (used to pick the singular vs plural fullform suffix) after the negative sign was already prefixed onto result[0], so filesize(-1, {fullform: true}) compared -1 === 1 and wrongly pluralized to "-1 bytes" instead of "-1 byte". Capture the magnitude before the sign is applied instead. --- src/helpers.js | 22 ++++++++++++---------- tests/unit/filesize.test.js | 10 ++++++++++ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/helpers.js b/src/helpers.js index e4f1c73..f8e18bb 100644 --- a/src/helpers.js +++ b/src/helpers.js @@ -402,6 +402,18 @@ export function decorateResult( bits, roundingFunc, ) { + // Capture the numeric value before the sign is prefixed and before + // formatting; a comma decimal separator (via separator or a locale such + // as de-DE) would otherwise make parseFloat read "1,5" as 1, and a + // negative sign would otherwise make -1 fail the "=== 1" singular check + // below, both wrongly selecting the plural unit name. + let numericValue; + if (typeof result[0] === "string") { + numericValue = parseFloat(result[0]); + } else { + numericValue = result[0]; + } + if (neg) { // `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 @@ -413,16 +425,6 @@ export function decorateResult( result[1] = symbols[result[1]]; } - // Capture the numeric value before formatting; a comma decimal separator - // (via separator or a locale such as de-DE) would otherwise make parseFloat - // read "1,5" as 1 and select the singular unit name. - let numericValue; - if (typeof result[0] === "string") { - numericValue = parseFloat(result[0]); - } else { - numericValue = result[0]; - } - result[0] = applyNumberFormatting( result[0], locale, diff --git a/tests/unit/filesize.test.js b/tests/unit/filesize.test.js index 9434777..baea6f6 100644 --- a/tests/unit/filesize.test.js +++ b/tests/unit/filesize.test.js @@ -268,6 +268,16 @@ describe("filesize", () => { ); }); + it("should keep the singular fullform name for negative one-magnitude values", () => { + assert.strictEqual(filesize(-1, { fullform: true }), "-1 byte"); + assert.strictEqual(filesize(-0.125, { bits: true, fullform: true }), "-1 bit"); + }); + + it("should keep the plural fullform name for negative values", () => { + assert.strictEqual(filesize(-2, { fullform: true }), "-2 bytes"); + assert.strictEqual(filesize(-0.25, { bits: true, fullform: true }), "-2 bits"); + }); + it("should handle bits fullform singular", () => { assert.strictEqual(filesize(0.125, { bits: true, fullform: true }), "1 bit"); });