diff --git a/package.json b/package.json index 380cd91..2f8109d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@curiousleaf/utils", "description": "A lightweight set of utilities", - "version": "1.0.28", + "version": "1.0.29", "license": "MIT", "type": "module", "author": { diff --git a/src/format/format.test.ts b/src/format/format.test.ts index 342d886..9332030 100644 --- a/src/format/format.test.ts +++ b/src/format/format.test.ts @@ -5,9 +5,46 @@ import { formatCurrency, formatIntervalAmount, formatMimeType, + formatNumber, formatToDecimals, } from "./format" +describe("formatNumber", () => { + it("formats numbers with compact notation (default)", () => { + expect(formatNumber(1000)).toBe("1K") + expect(formatNumber(1500)).toBe("1.5K") + expect(formatNumber(1000000)).toBe("1M") + }) + + it("formats numbers with standard notation", () => { + expect(formatNumber(1000, "standard")).toBe("1,000") + expect(formatNumber(1000000, "standard")).toBe("1,000,000") + }) + + it("formats numbers with different locales", () => { + expect(formatNumber(1000, "compact", "de-DE")).toBe("1000") + }) + + it("formats large numbers", () => { + expect(formatNumber(1000000000)).toBe("1B") + expect(formatNumber(1500000000)).toBe("1.5B") + }) + + it("formats small numbers", () => { + expect(formatNumber(0.1)).toBe("0.1") + expect(formatNumber(0.01)).toBe("0.01") + }) + + it("formats zero", () => { + expect(formatNumber(0)).toBe("0") + }) + + it("formats negative numbers", () => { + expect(formatNumber(-1000)).toBe("-1K") + expect(formatNumber(-1500000)).toBe("-1.5M") + }) +}) + describe("formatCurrency", () => { it("formats a number as currency", () => { expect(formatCurrency(1000)).toBe("$1,000") diff --git a/src/format/format.ts b/src/format/format.ts index 0ff19c1..e4408ed 100644 --- a/src/format/format.ts +++ b/src/format/format.ts @@ -2,8 +2,22 @@ * Utility functions for formatting data. */ +type Notation = Intl.NumberFormatOptions["notation"] type Currency = Intl.NumberFormatOptions["currency"] +/** + * Formats a number with thousands separators. + * @param number - The number to format. + * @param notation - The notation to use for formatting. Defaults to 'standard'. + * @param locale - The locale to use for formatting. Defaults to 'en-US'. + * @returns The formatted number as a string. + */ +export const formatNumber = (number: number, notation: Notation = "compact", locale = "en-US") => { + const formatter = new Intl.NumberFormat(locale, { notation }) + + return formatter.format(number) +} + /** * Formats a given amount of money into a currency string. * @param amount The amount of money to format.