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
2 changes: 1 addition & 1 deletion src/number.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, "");

Expand Down
17 changes: 9 additions & 8 deletions tests/number-formatter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
11 changes: 10 additions & 1 deletion tests/rifm-format.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 }),
});
Expand All @@ -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 () => {
Expand Down
Loading