### UI Styling with formatColor and format Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Example of using formatColor to get a color and format() to get the display string for UI styling. Requires importing formatColor and format. ```javascript const pattern = '[green]#,##0;[red]-#,##0'; const value = -1234.5; const color = formatColor(pattern, value); const formatted = format(pattern, value); // Apply color to rendered element element.style.color = color; element.textContent = formatted; ``` -------------------------------- ### Install numfmt via NPM Source: https://github.com/borgar/numfmt/blob/master/README.md Install the numfmt library using npm. This is the recommended way to add the library to your project if you do not wish to build it yourself. ```bash $ npm install numfmt ``` -------------------------------- ### Conditional Formatting Examples Source: https://github.com/borgar/numfmt/blob/master/_autodocs/README.md Demonstrates conditional formatting rules for numbers, including ranges and colors. ```javascript "[>100]#,##0;[<0]\"negative\";#,##0" "[Green]#,##0;[Red]-#,##0" "[>=0]#,##0.00;[Red]#,##0.00" ``` -------------------------------- ### Format with Different Locales Source: https://github.com/borgar/numfmt/blob/master/_autodocs/configuration.md Illustrates how the 'locale' option affects number formatting, showing examples for US, German, and French locales. ```javascript format('#,##0.00', 1234.5, { locale: 'en-US' }); // → "1,234.50" format('#,##0.00', 1234.5, { locale: 'de-DE' }); // → "1.234,50" format('#,##0.00', 1234.5, { locale: 'fr-FR' }); // → "1 234,50" ``` -------------------------------- ### Get Format Info for Percentage Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-info.md Parses a percentage format pattern and returns its properties. Results are cached for performance. ```javascript import { getFormatInfo } from 'numfmt'; // Percentage getFormatInfo('0.00%'); // → { // type: 'percent', // isDate: false, // isText: false, // isPercent: true, // maxDecimals: 2, // scale: 100, // color: 0, // parentheses: 0, // grouped: 0, // code: 'P2', // level: 10.6 // } ``` -------------------------------- ### Get Format Info for Currency Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-info.md Parses a currency format pattern and returns its properties. Results are cached for performance. ```javascript import { getFormatInfo } from 'numfmt'; // Currency pattern getFormatInfo('$#,##0.00'); // → { // type: 'currency', // isDate: false, // isText: false, // isPercent: false, // maxDecimals: 2, // scale: 1, // color: 0, // parentheses: 0, // grouped: 1, // code: 'C2', // level: 10.4 // } ``` -------------------------------- ### getFormatDateInfo Source: https://github.com/borgar/numfmt/blob/master/API.md Gets information about date codes use in a format string. ```APIDOC ## getFormatDateInfo(pattern) ### Description Gets information about date codes use in a format string. ### Method (Not specified, likely a function call) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) #### Parameters - **pattern** (string) - Required - A format pattern in the ECMA-376 number format. ### Request Example (Not specified) ### Response #### Success Response - **FormatDateInfo** - An object of format date properties. #### Response Example (Not specified) ``` -------------------------------- ### Get Format Info for Accounting with Colors and Parentheses Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-info.md Parses an accounting format pattern with specific color and parenthesis rules, returning its properties. Results are cached. ```javascript import { getFormatInfo } from 'numfmt'; // Accounting format with colors and parentheses getFormatInfo('[green]#,##0.00;[red](#,##0.00)'); // → { // type: 'currency', // isDate: false, // isText: false, // isPercent: false, // maxDecimals: 2, // scale: 1, // color: 1, // negative section has color // parentheses: 1, // positive section has parentheses // grouped: 1, // code: 'C2-()', // level: 10.4 // } ``` -------------------------------- ### Analyze format patterns Source: https://github.com/borgar/numfmt/blob/master/_autodocs/README.md Use getFormatInfo() to get details about a number format pattern and getFormatDateInfo() to extract date/time components from a pattern. ```javascript import { getFormatInfo, getFormatDateInfo } from 'numfmt'; getFormatInfo('#,##0.00'); // → { // type: 'number', // isDate: false, // isPercent: false, // maxDecimals: 2, // ... // } getFormatDateInfo('mm/dd/yyyy hh:mm:ss'); // → { // year: true, // month: true, // day: true, // hours: true, // minutes: true, // seconds: true, // clockType: 24 // } ``` -------------------------------- ### Get Format Info for Date Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-info.md Parses a date format pattern and returns its properties. Results are cached for performance. ```javascript import { getFormatInfo } from 'numfmt'; // Date pattern getFormatInfo('mm/dd/yyyy'); // → { // type: 'date', // isDate: true, // isText: false, // isPercent: false, // maxDecimals: 0, // scale: 1, // color: 0, // parentheses: 0, // grouped: 0, // code: 'D4', // level: 10.8 // } ``` -------------------------------- ### Get Format Info for Text-Only Pattern Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-info.md Parses a text-only format pattern and returns its properties. Results are cached for performance. ```javascript import { getFormatInfo } from 'numfmt'; // Text-only pattern getFormatInfo('@" USD"'); // → { // type: 'text', // isDate: false, // isText: true, // isPercent: false, // maxDecimals: 0, // scale: 1, // color: 0, // parentheses: 0, // grouped: 0, // code: 'G', // level: 15 // } ``` -------------------------------- ### Get Format Info for Scientific Notation Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-info.md Parses a scientific notation format pattern and returns its properties. Results are cached for performance. ```javascript import { getFormatInfo } from 'numfmt'; // Scientific notation getFormatInfo('0.00E+00'); // → { // type: 'scientific', // isDate: false, // isText: false, // isPercent: false, // maxDecimals: 2, // scale: 1, // color: 0, // parentheses: 0, // grouped: 0, // code: 'S2', // level: 6 // } ``` -------------------------------- ### Case-Insensitive Named Color Matching (Uppercase) Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Demonstrates that named color modifiers in patterns are case-insensitive, using an uppercase example. ```javascript formatColor('[RED]0', 0); ``` -------------------------------- ### Case-Insensitive Named Color Matching (Mixed Case) Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Demonstrates that named color modifiers in patterns are case-insensitive, using a mixed-case example. ```javascript formatColor('[ReD]0', 0); ``` -------------------------------- ### Basic Formatting and Parsing with Options Source: https://github.com/borgar/numfmt/blob/master/_autodocs/configuration.md Demonstrates how to use the format() and parseValue() functions with configuration options for locale and non-breaking space. ```javascript import { format, parseValue } from 'numfmt'; // Formatting with options format('#,##0.00', 1234.5, { locale: 'de-DE', nbsp: true }); // Parsing with options parseValue('1.234,5', { locale: 'de-DE' }); ``` -------------------------------- ### Currency Detection with getFormatInfo Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-info.md Demonstrates how getFormatInfo() detects currency symbols, with an option to limit detection to a specific currency. ```javascript // Detect any currency symbol getFormatInfo('€#,##0'); // → { type: 'currency', ... } // Limit detection to Euro getFormatInfo('€#,##0', { currency: '€' }); // → { type: 'currency', ... } // Euro not in pattern - not detected as currency getFormatInfo('€#,##0', { currency: '$' }); // → { type: 'number', ... } ``` -------------------------------- ### Default Options Reference Source: https://github.com/borgar/numfmt/blob/master/_autodocs/configuration.md This snippet shows the default configuration options defined within the library's `lib/options.js` file. It lists various settings and their default values. ```javascript // lib/options.js const defaultOptions = { overflow: '######', dateErrorThrows: false, dateErrorNumber: true, bigintErrorNumber: false, dateSpanLarge: true, leap1900: true, nbsp: false, throws: true, invalid: '######', locale: '', ignoreTimezone: false, grouping: [ 3, 3 ], indexColors: true, skipChar: '', repeatChar: '' }; ``` -------------------------------- ### Web/HTML Output Formatting Options Source: https://github.com/borgar/numfmt/blob/master/_autodocs/configuration.md Configuration options optimized for rendering formatted output in web or HTML contexts. This includes using non-breaking spaces and visible characters for fill and skip operations. ```javascript format(pattern, value, { nbsp: true, // Non-breaking spaces fillChar: '·', // Visible fill character skipChar: ' ' // Visible skip character }); ``` -------------------------------- ### Format and Parse with Locales Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/locale.md Demonstrates using the `format` and `parseValue` functions with specified locales to ensure correct number formatting and date parsing according to regional conventions. ```javascript import { format, parseValue } from 'numfmt'; // Format with locale format('#,##0.00', 1234.5, { locale: 'de-DE' }); // → "1.234,50" // Parse with locale parseValue("1.234,5", { locale: 'de-DE' }); // → { v: 1234.5, z: '#,##0.00' } // Date parsing respects locale month/day order parseValue("4/2/2025", { locale: 'en-US' }); // → { v: 45643, z: 'mm/dd/yyyy' } (April 2nd) parseValue("4/2/2025", { locale: 'de-DE' }); // → { v: 45642, z: 'dd/mm/yyyy' } (February 4th) ``` -------------------------------- ### Register and use custom locales Source: https://github.com/borgar/numfmt/blob/master/_autodocs/README.md Manage language and regional formatting by registering custom locale data with addLocale() and then using it with the format() function. ```javascript import { addLocale, getLocale } from 'numfmt'; // Register custom locale addLocale({ group: '.', decimal: ',', mmmm: ['Januar', 'Februar', ...], dddd: ['Sonntag', 'Montag', ...] }, 'de-DE'); // Use locale format('#,##0.00', 1234.5, { locale: 'de-DE' }); // → "1.234,50" // 70+ locales pre-registered: en, de, fr, es, ja, zh, ru, ar, ... ``` -------------------------------- ### getFormatInfo() and getFormatDateInfo() Source: https://github.com/borgar/numfmt/blob/master/_autodocs/README.md Inspect and analyze format patterns to understand their properties. `getFormatInfo` provides general details, while `getFormatDateInfo` specifically extracts date and time components. ```APIDOC ## getFormatInfo() and getFormatDateInfo() ### Description Inspect and analyze format patterns to understand their properties. `getFormatInfo` provides general details about a format pattern, and `getFormatDateInfo` specifically extracts date and time components used within a pattern. ### Method `getFormatInfo(formatPattern)` `getFormatDateInfo(formatPattern)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **formatPattern** (string) - Required - The Excel-style format pattern to analyze. ### Request Example ```javascript import { getFormatInfo, getFormatDateInfo } from 'numfmt'; getFormatInfo('#,##0.00'); // → { // type: 'number', // isDate: false, // isPercent: false, // maxDecimals: 2, // ... // } getFormatDateInfo('mm/dd/yyyy hh:mm:ss'); // → { // year: true, // month: true, // day: true, // hours: true, // minutes: true, // seconds: true, // clockType: 24 // } ``` ### Response #### Success Response - (object) - An object containing information about the format pattern. For `getFormatDateInfo`, it includes boolean flags for date/time components and clock type. ``` -------------------------------- ### Internationalization Formatting Options Source: https://github.com/borgar/numfmt/blob/master/_autodocs/configuration.md Recommended formatting options for international use, prioritizing user language, non-breaking spaces for rendering, and respecting the user's timezone. ```javascript format(pattern, value, { locale: userLanguage, // From user preferences nbsp: true, // Better HTML rendering ignoreTimezone: false // Respect user's timezone }); ``` -------------------------------- ### Utility functions for math and pattern analysis Source: https://github.com/borgar/numfmt/blob/master/_autodocs/README.md Provides utility functions such as round() for symmetric arithmetic rounding, dec2frac() for decimal to fraction conversion, and tokenize() for breaking patterns into components. ```javascript import { round, dec2frac, tokenize } from 'numfmt'; round(1.235, 2); // → 1.24 dec2frac(0.333333); // → [1, 3] tokenize('#,##0.00'); // → [{ type: 'hash', ... }, ...] ``` -------------------------------- ### Get Indexed Color as Number Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Extracts an indexed color from a pattern and returns its index number when the 'indexColors' option is false. Requires importing formatColor. ```javascript import { formatColor } from 'numfmt'; // Get the index instead formatColor('[Color 10]#,##0;[Color 5]#,##0', -50, { indexColors: false }); ``` -------------------------------- ### Format with Cyan Color Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Demonstrates using the '[Cyan]' named color modifier in a format pattern. ```javascript // All named colors formatColor('[Cyan]0', 0); ``` -------------------------------- ### Get Indexed Color as Hex Value Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Extracts an indexed color from a pattern and returns its hex value when the 'indexColors' option is true. Requires importing formatColor. ```javascript import { formatColor } from 'numfmt'; // Excel indexed color palette formatColor('[Color 10]#,##0;[Color 5]#,##0', -50, { indexColors: true }); ``` -------------------------------- ### Format with Blue Color Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Demonstrates using the '[Blue]' named color modifier in a format pattern. ```javascript // All named colors formatColor('[Blue]0', 0); ``` -------------------------------- ### Get Locale Data Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/locale.md Retrieves locale data for a given BCP 47 language tag. Falls back to the base language if an exact match is not found. Returns null if the locale is not registered. ```javascript import { getLocale } from 'numfmt'; // Exact match getLocale('en_US'); // → { group: ',', decimal: '.', ... } // Base language fallback getLocale('en_CA'); // → { group: ',', decimal: '.', ... } (falls back to en_US or en) // Not found getLocale('xx_YY'); // → null ``` -------------------------------- ### Format with White Color Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Demonstrates using the '[White]' named color modifier in a format pattern. ```javascript // All named colors formatColor('[White]0', 0); ``` -------------------------------- ### Handle Excel's 1900 Leap Year Bug Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/date-and-serial.md Demonstrates how `dateFromSerial` handles Excel's 1900 leap year bug by default. Use the `leap1900: false` option to get the correct date. Import 'dateFromSerial' from 'numfmt'. ```javascript import { dateFromSerial } from 'numfmt'; dateFromSerial(60); // Feb 29 in Excel (the "leap year bug") // → [ 1900, 2, 29, 0, 0, 0 ] // With leap1900 disabled dateFromSerial(60, { leap1900: false }); // → [ 1900, 3, 1, 0, 0, 0 ] (actual March 1) ``` -------------------------------- ### Format with Invalid Pattern (Safe Mode) Source: https://github.com/borgar/numfmt/blob/master/_autodocs/configuration.md Demonstrates how to use the 'throws: false' option to prevent errors when an invalid format pattern is encountered, outputting a default or custom invalid string. ```javascript // safe mode format('[invalid', 100, { throws: false }); // → "######" ``` -------------------------------- ### Configure nbsp for Formatting Source: https://github.com/borgar/numfmt/blob/master/_autodocs/configuration.md Use the `nbsp` option to control whether non-breaking spaces are used for spaces in the output. This is useful for HTML/CSS rendering where regular spaces might collapse. ```javascript // Regular space format('#,##0', 1000, { nbsp: false }); // → "1 000" (regular space) // Non-breaking space format('#,##0', 1000, { nbsp: true }); // → "1 000" (non-breaking space) ``` -------------------------------- ### FormatOptions Interface Source: https://github.com/borgar/numfmt/blob/master/_autodocs/types.md Defines the structure for options passed to format() and related functions, covering basic, date/time, overflow, and space/fill configurations. ```typescript interface FormatOptions { // Basic locale?: string; throws?: boolean; invalid?: string; // Date/Time leap1900?: boolean; ignoreTimezone?: boolean; dateErrorThrows?: boolean; dateErrorNumber?: boolean; dateSpanLarge?: boolean; // Overflow overflow?: string; bigintErrorNumber?: boolean; // Space/Fill nbsp?: boolean; skipChar?: string; fillChar?: string; // Format analysis (getFormatInfo only) currency?: string; // Color extraction (formatColor only) indexColors?: boolean; } ``` -------------------------------- ### Convert Boundary Serial Date to Components Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/date-and-serial.md Shows the conversion of the boundary serial date '1' to its date components. Ensure 'dateFromSerial' from 'numfmt' is imported. ```javascript import { dateFromSerial } from 'numfmt'; dateFromSerial(1); ``` -------------------------------- ### Excel Compatibility Formatting Options Source: https://github.com/borgar/numfmt/blob/master/_autodocs/configuration.md Configuration options recommended for maximum compatibility with Microsoft Excel. This includes enabling loud error reporting, specific date handling, and US locale formatting. ```javascript format(pattern, value, { throws: true, // Fail loudly on invalid patterns leap1900: true, // Required by ECMA-376 dateSpanLarge: false, // Use Excel date bounds locale: 'en-US' // US formatting }); ``` -------------------------------- ### round(), dec2frac(), tokenize(), isDateFormat(), isPercentFormat(), isTextFormat(), isValidFormat(), tokenTypes Source: https://github.com/borgar/numfmt/blob/master/_autodocs/README.md A collection of utility functions for mathematical operations, number-to-fraction conversion, pattern tokenization, and format validation. `tokenTypes` provides constants for token types. ```APIDOC ## Utilities ### Description A collection of utility functions for mathematical operations, number-to-fraction conversion, pattern tokenization, and format validation. `tokenTypes` provides constants for identifying different token types within a format pattern. ### Methods - `round(number, decimals)` - `dec2frac(decimal)` - `tokenize(formatPattern)` - `isDateFormat(formatPattern)` - `isPercentFormat(formatPattern)` - `isTextFormat(formatPattern)` - `isValidFormat(formatPattern)` - `tokenTypes` (object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **number** (number) - Required - The number to round. - **decimals** (number) - Required - The number of decimal places to round to. - **decimal** (number) - Required - The decimal number to convert to a fraction. - **formatPattern** (string) - Required - The format pattern string to analyze or tokenize. ### Request Example ```javascript import { round, dec2frac, tokenize, isDateFormat, isPercentFormat, isTextFormat, isValidFormat, tokenTypes } from 'numfmt'; round(1.235, 2); // → 1.24 dec2frac(0.333333); // → [1, 3] tokenize('#,##0.00'); // → [{ type: 'hash', ... }, ...] isDateFormat('mm/dd/yyyy'); // → true isPercentFormat('0%'); // → true isTextFormat('@'); // → true isValidFormat('#,##0.00'); // → true console.log(tokenTypes.hash); // → 'hash' ``` ### Response #### Success Response - `round`: (number) - The rounded number. - `dec2frac`: (Array) - An array representing the fraction `[numerator, denominator]`. - `tokenize`: (Array) - An array of token objects. - `isDateFormat`, `isPercentFormat`, `isTextFormat`, `isValidFormat`: (boolean) - True if the format matches the check, false otherwise. - `tokenTypes`: (object) - An object containing constants for token types. ``` -------------------------------- ### Check if Pattern Specifies Color Formatting Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Demonstrates how to use formatColor to determine if a given pattern includes any color formatting. ```javascript if (formatColor(pattern, value) !== null) { // Pattern uses colors } ``` -------------------------------- ### Format with Magenta Color Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Demonstrates using the '[Magenta]' named color modifier in a format pattern. ```javascript // All named colors formatColor('[Magenta]0', 0); ``` -------------------------------- ### addLocale() and getLocale() Source: https://github.com/borgar/numfmt/blob/master/_autodocs/README.md Manage language and regional formatting settings. `addLocale` allows registering custom locale data, while `getLocale` can be used to look up existing locale information. ```APIDOC ## addLocale() and getLocale() ### Description Manage language and regional formatting settings. `addLocale` allows you to register custom locale data for specific formatting rules (like decimal separators, month names, etc.). `getLocale` can be used to look up the data for a pre-registered locale. ### Method `addLocale(localeData, localeTag)` `getLocale(localeTag)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **localeData** (object) - Required - An object containing locale-specific data (e.g., `group`, `decimal`, `mmmm`, `dddd`). - **localeTag** (string) - Required - The BCP 47 language tag for the locale (e.g., 'de-DE'). ### Request Example ```javascript import { addLocale, getLocale } from 'numfmt'; // Register custom locale addLocale({ group: '.', decimal: ',', mmmm: ['Januar', 'Februar', ...], dddd: ['Sonntag', 'Montag', ...] }, 'de-DE'); // Use locale format('#,##0.00', 1234.5, { locale: 'de-DE' }); // → "1.234,50" // 70+ locales pre-registered: en, de, fr, es, ja, zh, ru, ar, ... ``` ### Response #### Success Response - `addLocale`: (void) - This function does not return a value. - `getLocale`: (object | undefined) - The locale data object if found, otherwise undefined. ``` -------------------------------- ### Format with Black Color Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Demonstrates using the '[Black]' named color modifier in a format pattern. ```javascript // All named colors formatColor('[Black]0', 0); ``` -------------------------------- ### Format with Red Color Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Demonstrates using the '[Red]' named color modifier in a format pattern. ```javascript // All named colors formatColor('[Red]0', 0); ``` -------------------------------- ### Excel Compatibility Formatting Source: https://github.com/borgar/numfmt/blob/master/_autodocs/README.md Use this configuration for formatting numbers to be compatible with Microsoft Excel. ```javascript format(pattern, value, { leap1900: true, dateSpanLarge: false, throws: true }); ``` -------------------------------- ### Error Handling for Invalid Pattern (Throw Mode) Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Shows how formatColor throws an error when an invalid pattern is provided and 'throws' is true (default). Requires importing formatColor. ```javascript import { formatColor } from 'numfmt'; // Invalid pattern in throw mode try { formatColor('[invalid', 100); } catch (e) { // Throws SyntaxError } ``` -------------------------------- ### CommonJS Import Source: https://github.com/borgar/numfmt/blob/master/_autodocs/README.md Import format and parseValue functions for use in CommonJS environments like Node.js. ```javascript const { format, parseValue } = require('numfmt'); ``` -------------------------------- ### format() Function Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format.md The primary function for formatting values. It takes a pattern, a value, and optional configuration to produce a formatted string. Supports various data types including numbers, dates, booleans, and strings. ```APIDOC ## format() Function ### Description Formats a value as a string according to an ECMA-376 number format pattern. This is the main entry point for number formatting. ### Signature ```javascript format(pattern: string, value: any, options?: object): string ``` ### Parameters #### Path Parameters * **pattern** (string) - Required - A format pattern in ECMA-376 syntax (e.g., `"#,##0.00"`, `"mm/dd/yyyy"`) * **value** (any) - Required - The value to format: number, Date, boolean, string, array, null * **options** (object) - Optional - Configuration object for advanced formatting. ### Options #### Basic Options * **locale** (string) - Optional - BCP 47 language tag (e.g., `"en-US"`, `"fr-FR"`). Defaults to `""` (English). * **throws** (boolean) - Optional - If `true`, throws an error on invalid patterns. Defaults to `true`. * **invalid** (string) - Optional - String emitted when pattern parsing fails in non-throw mode. Defaults to `"######"`. #### Date/Time Options * **leap1900** (boolean) - Optional - Simulate the Lotus 1-2-3 1900 leap year bug. Defaults to `true`. * **ignoreTimezone** (boolean) - Optional - When `true`, converts Date objects without timezone offset adjustment. Defaults to `false`. * **dateErrorThrows** (boolean) - Optional - If `true`, throws when formatting dates outside valid range. Defaults to `false`. * **dateErrorNumber** (boolean) - Optional - If `true`, switches to General format for out-of-bounds dates. Defaults to `true`. * **dateSpanLarge** (boolean) - Optional - If `true`, extends date range to 0–99999. Defaults to `true`. #### Overflow Options * **overflow** (string) - Optional - String emitted when a date fails to format due to bounds. Defaults to `"######"`. * **bigintErrorNumber** (boolean) - Optional - If `true`, formats out-of-bounds bigints as plain number strings. Defaults to `false`. #### Space/Fill Options * **nbsp** (boolean) - Optional - If `true`, uses non-breaking space (` `) instead of regular space. Defaults to `false`. * **skipChar** (string) - Optional - When format contains `_`, emit this character followed by the next. Defaults to `""`. * **fillChar** (string) - Optional - When format contains `*`, emit this character followed by the next. Defaults to `""`. ### Return Value **Type**: `string` A formatted representation of the input value according to the pattern and options. ### Examples #### Basic Numbers ```javascript import { format } from 'numfmt'; // Integer with grouping format('#,##0', 1234567); // → "1,234,567" // Decimal with fixed places format('#,##0.00', 1234.5); // → "1,234.50" // Scientific notation format('0.00E+00', 12345); // → "1.23E+04" ``` #### Percentages ```javascript format('0%', 0.75); // → "75%" format('0.00%', 0.333333); // → "33.33%" ``` #### Currency ```javascript format('$#,##0.00', 1234.5); // → "$1,234.50" format('[DBNum1][$-804]0', 123, { locale: 'zh_CN' }); // → Format in Chinese with DBNum modifier ``` #### Dates and Times ```javascript // Date object format('mm/dd/yyyy', new Date(2025, 0, 15)); // → "01/15/2025" // Array format [year, month, day, hour, minute, second] format('yyyy-mm-dd hh:mm:ss', [2025, 1, 15, 14, 30, 0]); // → "2025-01-15 14:30:00" // Serial date (Excel-style) format('mmm dd, yyyy', 45640); // → "Jan 15, 2025" ``` #### Conditional Formatting ```javascript // Different format for positive/negative/zero format('[Green]#,##0;[Red]-#,##0;[Blue]0', 100); // → "100" in green format('[Green]#,##0;[Red]-#,##0;[Blue]0', -50); // → "-50" in red ``` #### With Locale ```javascript format('#,##0.00', 1234.5, { locale: 'de-DE' }); // → "1.234,50" (German uses . for thousands, , for decimal) format('#,##0.00', 1234.5, { locale: 'en-GB' }); // → "1,234.50" (British uses , for thousands, . for decimal) ``` #### Error Handling ```javascript // Invalid pattern - throws by default try { format('[invalid', 100); } catch (e) { // Catches SyntaxError } // Invalid pattern - safe mode format('[invalid', 100, { throws: false }); // → "######" ``` ``` -------------------------------- ### Format values with Excel patterns Source: https://github.com/borgar/numfmt/blob/master/_autodocs/README.md Use the format() function to apply Excel-style number, percentage, currency, and date formats to values. Supports custom locales for regional formatting. ```javascript import { format } from 'numfmt'; // Numbers format('#,##0.00', 1234.56); // → "1,234.56" format('0%', 0.75); // → "75%" format('$#,##0', 5000); // → "$5,000" // Dates format('mm/dd/yyyy', new Date()); // → "05/30/2025" format('mmm dd, yyyy', [2025, 1, 15]); // → "Jan 15, 2025" // With locale format('#,##0.00', 1234.5, { locale: 'de-DE' }); // → "1.234,50" ``` -------------------------------- ### getFormatInfo() Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-info.md Retrieves detailed properties about a format pattern, including its type, decimal places, color and parenthesis indicators, and an Excel CELL function compatible format code. Results are cached for performance. ```APIDOC ## getFormatInfo() ### Description The `getFormatInfo()` function parses a format pattern and returns an object containing its properties: type (currency, date, number, etc.), supported decimal places, color and parenthesis indicators (Excel CELL function compatibility), and a format code string that matches Excel's `CELL("format")` output. Results are cached, so subsequent calls with the same pattern are fast. ### Parameters #### Path Parameters - **pattern** (string) - Required - An ECMA-376 format pattern - **options** (object) - Optional - Configuration options - **currency** (string) - Optional - Limit currency detection to a specific symbol. If omitted, all known currency symbols are recognized ### Return Value **Type**: `FormatInfo` An object with the following structure: ```javascript { type: string, // "currency" | "date" | "datetime" | "time" | // "number" | "grouped" | "percent" | "scientific" | // "fraction" | "text" | "general" | "error" isDate: boolean, // true if pattern contains date symbols isText: boolean, // true if pattern is text-only (@) isPercent: boolean, // true if pattern contains % operator maxDecimals: number, // maximum decimal places (or 9 for General) scale: number, // multiplier (e.g., 100 for percentages) color: 0 | 1, // 1 if negative section has color (CELL compatibility) parentheses: 0 | 1, // 1 if positive section has parentheses (CELL compatibility) grouped: 0 | 1, // 1 if uses thousands separator code: string, // Excel CELL("format") code (e.g., "C0-", "D1") level: number // Specificity ranking for pattern comparison } ``` ### Examples ```javascript import { getFormatInfo } from 'numfmt'; // Currency pattern getFormatInfo('$#,##0.00'); // → { // type: 'currency', // isDate: false, // isText: false, // isPercent: false, // maxDecimals: 2, // scale: 1, // color: 0, // parentheses: 0, // grouped: 1, // code: 'C2', // level: 10.4 // } // Date pattern getFormatInfo('mm/dd/yyyy'); // → { // type: 'date', // isDate: true, // isText: false, // isPercent: false, // maxDecimals: 0, // scale: 1, // color: 0, // parentheses: 0, // grouped: 0, // code: 'D4', // level: 10.8 // } // Percentage getFormatInfo('0.00%'); // → { // type: 'percent', // isDate: false, // isText: false, // isPercent: true, // maxDecimals: 2, // scale: 100, // color: 0, // parentheses: 0, // grouped: 0, // code: 'P2', // level: 10.6 // } // Accounting format with colors and parentheses getFormatInfo('[green]#,##0.00;[red](#,##0.00)'); // → { // type: 'currency', // isDate: false, // isText: false, // isPercent: false, // maxDecimals: 2, // scale: 1, // color: 1, // negative section has color // parentheses: 1, // positive section has parentheses // grouped: 1, // code: 'C2-()', // level: 10.4 // } // Scientific notation getFormatInfo('0.00E+00'); // → { // type: 'scientific', // isDate: false, // isText: false, // isPercent: false, // maxDecimals: 2, // scale: 1, // color: 0, // parentheses: 0, // grouped: 0, // code: 'S2', // level: 6 // } // Text-only pattern getFormatInfo('@" USD"'); // → { // type: 'text', // isDate: false, // isText: true, // isPercent: false, // maxDecimals: 0, // scale: 1, // color: 0, // parentheses: 0, // grouped: 0, // code: 'G', // level: 15 // } ``` ### Currency Detection ```javascript // Detect any currency symbol getFormatInfo('€#,##0'); // → { type: 'currency', ... } // Limit detection to Euro getFormatInfo('€#,##0', { currency: '€' }); // → { type: 'currency', ... } // Euro not in pattern - not detected as currency getFormatInfo('€#,##0', { currency: '$' }); // → { type: 'number', ... } ``` ``` -------------------------------- ### tokenize() Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/utilities.md Breaks a format pattern string into individual tokens for analysis. ```APIDOC ## tokenize(pattern) ### Description Parses a format pattern string and returns an array of tokens. Each token includes its type, value, and raw source string. This function is useful for inspecting the structure of format patterns or implementing custom pattern analyzers. ### Parameters #### Parameters - **pattern** (string) - Required - An ECMA-376 format pattern string. ### Return Value **Type**: `FormatToken[]` An array of token objects, where each object has the following structure: ```javascript interface FormatToken { type: string; // Token type (e.g., "zero", "hash", "point") value: any; // Cleaned value (e.g., "." for point) raw: string; // Original source from pattern } ``` ``` -------------------------------- ### Format with Green Color Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Demonstrates using the '[Green]' named color modifier in a format pattern. ```javascript // All named colors formatColor('[Green]0', 0); ``` -------------------------------- ### parseTime() Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/parsing.md Parses time-of-day strings into fractional day values (0–1). It supports 12-hour or 24-hour formats, with or without seconds. ```APIDOC ## parseTime() ### Description Parses time-of-day strings into fractional day values (0–1). It supports 12-hour or 24-hour formats, with or without seconds. ### Signature ```javascript parseTime(value: string, options?: object): ParseData | null ``` ### Parameters #### Path Parameters - **value** (string) - Required - Time string to parse #### Query Parameters - **options** (object) - Optional - Configuration options - **options.locale** (string) - Optional - BCP 47 tag for AM/PM string in locale ### Return Value **Type**: `ParseData | null` ### Examples ```javascript import { parseTime } from 'numfmt'; // 24-hour format parseTime("14:30"); // → { v: 0.604166..., z: 'hh:mm' } parseTime("14:30:45"); // → { v: 0.604513..., z: 'hh:mm:ss' } parseTime("0:00:00"); // → { v: 0, z: 'h:mm:ss' } // 12-hour format parseTime("2:30 PM"); // → { v: 0.604166..., z: 'h:mm AM/PM' } parseTime("02:30:45 AM"); // → { v: 0.104513..., z: 'hh:mm:ss AM/PM' } parseTime("12:30 AM"); // → { v: 0.020833..., z: 'hh:mm AM/PM' } // Midnight // Fractional seconds parseTime("14:30:45.1234"); // → { v: 0.604513..., z: 'hh:mm:ss' } // Invalid or incomplete parseTime("not a time"); // → null parseTime("25:00"); // → null parseTime("14:30:60"); // → null ``` ``` -------------------------------- ### tokenize(pattern) Source: https://github.com/borgar/numfmt/blob/master/API.md Breaks a format pattern string into a list of tokens. Each token is represented as an object with its type, value, and raw string representation. ```APIDOC ## tokenize(pattern) ### Description Breaks a format pattern string into a list of tokens. ### Method N/A (Function Call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response `Array` – a list of tokens. Each token object has the following structure: ```js { type: 'string', value: 'string', raw: 'string' } ``` #### Response Example ```js [ { type: 'zero', value: '0', raw: '0' }, { type: 'point', value: '.', raw: '.' }, { type: 'zero', value: '0', raw: '0' }, { type: 'percent', value: '%', raw: '%' } ] ``` ``` -------------------------------- ### Format a Number Source: https://github.com/borgar/numfmt/blob/master/README.md Use the format function to format a number according to a specified format string. Import the function from the 'numfmt' library. ```javascript import { format } from "numfmt"; const output = format("#,##0.00", 1234.56); console.log(output); ``` -------------------------------- ### Format with Invalid Pattern (Throw Mode) Source: https://github.com/borgar/numfmt/blob/master/_autodocs/configuration.md Shows the default behavior of the format() function when an invalid pattern is provided, which is to throw a SyntaxError. ```javascript // throw mode (default) try { format('[invalid', 100); } catch (e) { console.log(e.message); } ``` -------------------------------- ### Custom Formatting Options Source: https://github.com/borgar/numfmt/blob/master/_autodocs/README.md Customize formatting with specific fill and skip characters, and non-breaking space. ```javascript format(pattern, value, { fillChar: '·', skipChar: ' ', nbsp: true }); ``` -------------------------------- ### Format Percentages Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format.md Format numbers as percentages with optional decimal places. ```javascript format('0%', 0.75); // → "75%" format('0.00%', 0.333333); // → "33.33%" ``` -------------------------------- ### Internationalization Formatting Source: https://github.com/borgar/numfmt/blob/master/_autodocs/README.md Apply internationalization settings for formatting, including locale and non-breaking space. ```javascript format(pattern, value, { locale: userLanguage, nbsp: true }); ``` -------------------------------- ### Token Types Constant Source: https://github.com/borgar/numfmt/blob/master/API.md Provides a dictionary of all possible token types used in format patterns. Useful for identifying and processing different parts of a pattern. ```javascript tokenTypes = `Readonly>` ``` -------------------------------- ### Format Value with Color Pattern Source: https://github.com/borgar/numfmt/blob/master/API.md Formats a value according to a pattern that includes color definitions. Returns the color name if specified and applicable, otherwise null. ```javascript const color = formatColor("[green]#,##0;[red]-#,##0", -10); console.log(color); // "red" ``` ```javascript const color = formatColor("[green]#,##0;-#,##0", -10); console.log(color); // null ``` -------------------------------- ### Error Handling for Invalid Pattern (Safe Mode) Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Shows how formatColor returns null for an invalid pattern when the 'throws' option is set to false. Requires importing formatColor. ```javascript import { formatColor } from 'numfmt'; // Invalid pattern in safe mode formatColor('[invalid', 100, { throws: false }); ``` -------------------------------- ### Format with Locale Options Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format.md Apply locale-specific number formatting for thousands separators and decimal points. Uses the 'locale' option. ```javascript format('#,##0.00', 1234.5, { locale: 'de-DE' }); // → "1.234,50" (German uses . for thousands, , for decimal) format('#,##0.00', 1234.5, { locale: 'en-GB' }); // → "1,234.50" (British uses , for thousands, . for decimal) ``` -------------------------------- ### Format with Yellow Color Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-color.md Demonstrates using the '[Yellow]' named color modifier in a format pattern. ```javascript // All named colors formatColor('[Yellow]0', 0); ``` -------------------------------- ### getFormatDateInfo() Source: https://github.com/borgar/numfmt/blob/master/_autodocs/api-reference/format-info.md Retrieves information about date and time components used in a format pattern, indicating which components are present and whether 12-hour or 24-hour time notation is used. ```APIDOC ## getFormatDateInfo() ### Description The `getFormatDateInfo()` function returns an object indicating which date and time components are present in a format pattern, and whether it uses 12-hour or 24-hour time notation. ### Parameters #### Path Parameters - **pattern** (string) - Required - An ECMA-376 format pattern ``` -------------------------------- ### Google Sheets Compatibility Formatting Options Source: https://github.com/borgar/numfmt/blob/master/_autodocs/configuration.md Configuration options to achieve behavior consistent with Google Sheets. This involves graceful error handling, extended date range support, and specific error number formatting. ```javascript format(pattern, value, { throws: false, // Fail gracefully dateSpanLarge: true, // Extended date range dateErrorNumber: true // Format out-of-bounds as numbers }); ``` -------------------------------- ### getFormatInfo Source: https://github.com/borgar/numfmt/blob/master/API.md Retrieves information about a formatting pattern. Options can be provided to customize the information retrieval. ```APIDOC ## getFormatInfo( pattern, [options] ) ### Description Retrieves information about a formatting pattern. Options can be provided to customize the information retrieval. ### Parameters #### Path Parameters - **pattern** (string) - Required - The formatting pattern. - **options** (object) - Optional - Options for information retrieval. ``` -------------------------------- ### ESM Import Source: https://github.com/borgar/numfmt/blob/master/_autodocs/README.md Import format and parseValue functions using ECMAScript Modules (ESM) syntax. ```javascript import { format, parseValue } from 'numfmt'; ``` -------------------------------- ### Browser Script Tag Usage Source: https://github.com/borgar/numfmt/blob/master/_autodocs/README.md Include the numfmt library via a script tag and use its functions in the browser. ```javascript ```