diff --git a/src/number.ts b/src/number.ts index ba5059c..ce26422 100644 --- a/src/number.ts +++ b/src/number.ts @@ -45,7 +45,7 @@ export const createNumberFormatter = (options: NumberFormatterOptions = {}): Num const decimalIndex = acceptsFraction ? value.indexOf(decimalSeparator) : -1; const integerSource = decimalIndex < 0 ? value : value.slice(0, decimalIndex); const fractionSource = decimalIndex < 0 ? "" : value.slice(decimalIndex + 1); - const negative = allowNegative && value.includes("-"); + const negative = allowNegative && value.startsWith("-"); let integer = integerSource.replace(/\D/g, "").replace(/^0+(?=\d)/, ""); let fraction = fractionSource.replace(/\D/g, ""); diff --git a/tests/number-formatter.test.ts b/tests/number-formatter.test.ts index 64c53b3..7df4a69 100644 --- a/tests/number-formatter.test.ts +++ b/tests/number-formatter.test.ts @@ -24,14 +24,15 @@ describe("number formatter", () => { }); test("supports signs, fixed precision, custom grouping, and disabled grouping", () => { - expect( - createNumberFormatter({ - locales: "en-IN", - allowNegative: true, - minimumFractionDigits: 2, - maximumFractionDigits: 2, - }).format("-$12345678.9"), - ).toBe("-1,23,45,678.90"); + const signed = createNumberFormatter({ + locales: "en-IN", + allowNegative: true, + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }); + + expect(signed.format("-$12345678.9")).toBe("-1,23,45,678.90"); + expect(signed.format("1234-5678.9")).toBe("1,23,45,678.90"); expect( createNumberFormatter({ useGrouping: false, maximumFractionDigits: 0 }).format("12,345"), diff --git a/tests/rifm-format.browser.test.tsx b/tests/rifm-format.browser.test.tsx index 09bc198..f32fce6 100644 --- a/tests/rifm-format.browser.test.tsx +++ b/tests/rifm-format.browser.test.tsx @@ -35,7 +35,7 @@ test("format works with real browser input", async () => { expect(await exec({ type: "PUT_SYMBOL", payload: "x" })).toBe("1|2’345"); }); -test("keeps the caret after a negative sign", async () => { +test("handles negative signs without moving or truncating digits", async () => { exec = createBrowserExec({ ...createNumberFormatter({ allowNegative: true, maximumFractionDigits: 0 }), }); @@ -49,6 +49,15 @@ test("keeps the caret after a negative sign", async () => { }); expect(await exec({ type: "PUT_SYMBOL", payload: "-" })).toBe("-|123"); + + exec.cleanup(); + exec = createBrowserExec({ + ...createNumberFormatter({ allowNegative: true, maximumFractionDigits: 0 }), + initialValue: "12345", + }); + + expect(await exec({ type: "MOVE_CARET", payload: 2 })).toBe("12|,345"); + expect(await exec({ type: "PUT_SYMBOL", payload: "-" })).toBe("12|,345"); }); test("format with custom accept works with real browser input", async () => {