Skip to content

Latest commit

History

History
667 lines (452 loc) · 48.4 KB

File metadata and controls

667 lines (452 loc) · 48.4 KB

Numfmt API

Functions

Constant

Types

Functions

# addLocale( localeSettings, l4e ) ⇒ LocaleData

Register locale data for a language so for use when formatting.

Any partial set of properties may be returned to have the defaults used where properties are missing.

See also: {LocaleData}.

Parameters
NameTypeDefaultDescription
localeSettingsobjectA collection of settings for a locale.
localeSettings.[ampm]Array<string>["AM","PM"]How AM and PM should be presented.
localeSettings.[bool]Array<string>["TRUE", "FALSE"]How TRUE and FALSE should be presented.
localeSettings.[ddd]Array<string>["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]Shortened day names (e.g. Wed)
localeSettings.[dddd]Array<string>["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]Long day names (e.g. Wednesday)
localeSettings.[decimal]string"."Symbol used to separate integers from fractions (usually .)
localeSettings.[exponent]string"E"Symbol used to indicate an exponent (usually E)
localeSettings.[group]string"\u00a0"Symbol used as a grouping separator (1,000,000 uses ,)
localeSettings.[infinity]string"∞"Symbol used to indicate infinite values ()
localeSettings.[mmm]Array<string>["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]Short month names for the Gregorian calendar (e.g. Nov)
localeSettings.[mmm6]Array<string>["Muh.", "Saf.", "Rab. I", "Rab. II", "Jum. I", "Jum. II", "Raj.", "Sha.", "Ram.", "Shaw.", "Dhuʻl-Q.", "Dhuʻl-H."]Short month names for the Islamic calendar (e.g. Raj.)
localeSettings.[mmmm]Array<string>["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]Long month names for the Gregorian calendar (e.g. November)
localeSettings.[mmmm6]Array<string>["Muharram", "Safar", "Rabiʻ I", "Rabiʻ II", "Jumada I", "Jumada II", "Rajab", "Shaʻban", "Ramadan", "Shawwal", "Dhuʻl-Qiʻdah", "Dhuʻl-Hijjah"]Long month names for the Islamic calendar (e.g. Rajab)
localeSettings.[nan]string"NaN"Symbol used to indicate NaN values (NaN)
localeSettings.[negative]string"-"Symbol used to indicate positive numbers (usually -)
localeSettings.[percent]string"%"Symbol used to indicate a percentage (usually %)
localeSettings.[positive]string"+"Symbol used to indicate positive numbers (usually +)
localeSettings.[preferMDY]booleanfalseIs the prefered date format month first (12/31/2025) or day first (31/12/2025)
l4estringA string BCP 47 tag of the locale.
Returns

LocaleData – - A full collection of settings for a locale


# dateFromSerial( serialDate, [options = {}] ) ⇒ Array<number>

Convert a spreadsheet serial date to an array of date parts. Accurate to a second.

// output as [ Y, M, D, h, m, s ]dateFromSerial(28627);// [ 1978, 5, 17, 0, 0, 0 ]
Parameters
NameTypeDefaultDescription
serialDatenumberThe date
[options]object{}The options
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug.
Returns

Array<number> – returns an array of date parts


# dateToSerial( date, [options = {}] ) ⇒ number | null

Convert a native JavaScript Date, or array to an spreadsheet serial date.

Returns a serial date number if input was a Date object or an array of numbers, a null.

// input as DatedateToSerial(newDate(1978,5,17));// 28627// input as [ Y, M, D, h, m, s ]dateToSerial([1978,5,17]);// 28627// other inputdateToSerial("something else");// null
Parameters
NameTypeDefaultDescription
dateDate | Array<number>The date
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally time zone will be taken into account. This makes the conversion to serial date ignore the timezone offset.
Returns

number | null – The date as a spreadsheet serial date, or null.


# format( pattern, value, [options = {}] ) ⇒ string

Formats a value as a string and returns the result.

  • Dates are normalized to spreadsheet style serial dates and then formatted. - Booleans are emitted as uppercase "TRUE" or "FALSE". - Null and Undefined will return an empty string "". - Any non number values will be stringified and passed through the text section of the format pattern. - NaNs and infinites will use the corresponding strings from the active locale.
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].bigintErrorNumberbooleanfalseShould the formatter switch to a plain string number format when trying to format a bigint that is out of bounds?
[options].dateErrorNumberbooleantrueShould the formatter switch to a General number format when trying to format a date that is out of bounds?
[options].dateErrorThrowsbooleanfalseShould the formatter throw an error when trying to format a date that is out of bounds?
[options].dateSpanLargebooleantrueExtends the allowed range of dates from Excel bounds (1900–9999) to Google Sheet bounds (0–99999).
[options].fillCharboolean""When the formatter encounters * it normally emits nothing instead of the * and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].invalidstring"######"The string emitted when no-throw mode fails to parse a pattern.
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug. It is a requirement in the Ecma OOXML specification so it is on by default.
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
[options].nbspbooleanfalseBy default the output will use a regular space, but in many cases you may desire a non-breaking-space instead.
[options].overflowstring"######"The string emitted when a formatter fails to format a date that is out of bounds.
[options].skipCharboolean""When the formatter encounters _ it normally emits a single space instead of the _ and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string – A formatted value


# formatColor( pattern, value, [options = {}] ) ⇒ string | number | null

Find the color appropriate to a value as dictated by a format pattern.

If the pattern defines colors, this function will emit the color appropriate to the value. If no colors were specified this function returns undefined.

constcolor=formatColor("[green]#,##0;[red]-#,##0",-10);console.log(color);// "red"constcolor=formatColor("[green]#,##0;-#,##0",-10);console.log(color);// null
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].indexColorsbooleantrueWhen indexed color modifiers are used ([Color 1]) the formatter will convert the index into the corresponding hex color of the default palette. When this option is set to false, the number will instead by emitted allowing you to index against a custom palette.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string | number | null – A string color value as described by the pattern or a number if the indexColors option has been set to false.


# getFormatDateInfo( pattern ) ⇒ FormatDateInfo

Gets information about date codes use in a format string.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

FormatDateInfo – An object of format date properties.


# getFormatInfo( pattern, [options = {}] ) ⇒ FormatInfo

Returns an object detailing the properties and internals of a format parsed format pattern.

Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
[options]object{}Options
[options].currencystringLimit the patterns identified as currency to those that use the give string. If nothing is provided, patterns will be tagged as currency if one of the following currency symbols is used: ¤$£¥֏؋৳฿៛₡₦₩₪₫€₭₮₱₲₴₸₹₺₼₽₾₿
Returns

FormatInfo – An object of format properties.


# getLocale( locale ) ⇒ LocaleData | null

Used by the formatter to pull a locate from its registered locales. If subtag isn't available but the base language is, the base language is used. So if en-CA is not found, the formatter tries to find en else it returns a null.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale, or an Excel locale code.
Returns

LocaleData | null – - An object of format date properties.


# isDateFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a date pattern.

The pattern is considered a date pattern if any of its sections contain a date symbol (such as Y or H). Each section is restricted to be either a number or date format.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isPercentFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a percentage pattern.

The pattern is considered a percentage pattern if any of its sections contains an unescaped percentage symbol.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isTextFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a text only pattern.

The pattern is considered text only if its definition is composed of a single section that includes that text symbol (@).

For example @ or @" USD" are text patterns but #;@ is not.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isValidFormat( pattern ) ⇒ boolean

Determine if a given format pattern is valid.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is valid, False otherwise.


# parseBool( value, [options = {}] ) ⇒ ParseData | null

Parse a string input and return its boolean value. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with one property:

  • v: the parsed value.

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe supposed boolean to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseDate( value, [options = {}] ) ⇒ ParseData | null

Parse a date or datetime string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseLocale( locale ) ⇒ LocaleToken

Parse a regular IETF BCP 47 locale tag and emit an object of its parts. Irregular tags and subtags are not supported.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale.
Returns

LocaleToken – - An object describing the locale.


# parseNumber( value, [options = {}] ) ⇒ ParseData | null

Parse a numeric string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. * z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe number to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseTime( value, [options = {}] ) ⇒ ParseData | null

Parse a time string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseValue( value, [options = {}] ) ⇒ ParseData | null

Attempt to parse a "spreadsheet input" string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: The parsed value. For dates, this will be an Excel style serial date. - z: (Optionally) the number format string of the input. This property will not be present if it amounts to the General format.

parseValue() recognizes a wide range of dates and date-times, times, numbers, and booleans. Some examples:

// basic numberparseValue("-123");// { v: -123 }// formatted numberparseValue("$1,234");// { v: 1234, z: "$#,##0" }// a percentparseValue("12.3%");// { v: 0.123, z: "0.00%" }// a dateparseValue("07 October 1984");// { v: 30962, z: 'dd mmmm yyyy' }// an ISO formatted date-timeparseValue("1984-09-10 11:12:13.1234");// { v: 30935.46681855787, z: "yyyy-mm-dd hh:mm:ss" }// a booleanparseValue("false");// { v: false }

The formatting string outputted may not correspond exactly to the input. Rather, is it composed of certain elements which the input controls. This is comparable to how Microsoft Excel and Google Sheets parse pasted input. Some things you may expect:

  • Whitespace is ignored. - Decimal fractions are always represented by .00 regardless of how many digits were shown in the input. - Negatives denoted by parentheses [(1,234)] will not include the parentheses in the format string (the value will still by negative.) - All "scientific notation" returns the same format: 0.00E+00.

Internally the parser calls, parseNumber, parseDate, parseTime and parseBool. They work in the same way except with a more limited scope. You may want those function if you are limiting input to a smaller scope.

Be warned that the parser do not (yet) take locale into account so all input is assumed to be in "en-US". This means that 1,234.5 will parse, but 1.234,5 will not. Similarly, the order of date parts will be US centric. This may change in the future so be careful what options you pass the functions.

Parameters
NameTypeDefaultDescription
valuestringThe value to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# round( number, [places] ) ⇒ number

Return a number rounded to the specified amount of places. This is the rounding function used internally by the formatter (symmetric arithmetic rounding).

Parameters
NameTypeDefaultDescription
numbernumberThe number to round.
[places]number0The number of decimals to round to.
Returns

number – A rounded number.


# tokenize( pattern ) ⇒ Array<FormatToken>

Breaks a format pattern string into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: 'zero',value: '0',raw: '0'},{type: 'point',value: '.',raw: '.'},{type: 'zero',value: '0',raw: '0'},{type: 'percent',value: '%',raw: '%'}]

Token types may be found as an Object as the tokenTypes export of the package.

Parameters
NameTypeDescription
patternstringThe format pattern
Returns

Array<FormatToken> – a list of tokens


Constant

# tokenTypes = Readonly<Record<string, string>>

A dictionary of the types used to identify token variants.

See also:tokenize.

Properties
NameTypeDescription
AMPMstringAM/PM operator (AM/PM, A/P)
BREAKstringSemicolon operator indicating a break between format sections (;)
CALENDARstringCalendar modifier (B2)
CHARstringSingle non-operator character (m)
COLORstringColor modifier ([Black], [color 5])
COMMAstringPlain non-operator comma (,)
CONDITIONstringCondition modifier for a section ([>=10])
DATETIMEstringDate-time operator (mmmm, YY)
DBNUMstringNumber display modifier ([DBNum23])
DIGITstringA digit between 1 and 9 (3)
DURATIONstringTime duration ([ss])
ERRORstringUnidentifiable or illegal character (Ň)
ESCAPEDstringEscaped character (\E)
EXPstringExponent operator (E+)
FILLstringFill with char operator and operand (*_)
GENERALstringGeneral format operator (General)
GROUPstringNumber grouping operator (,)
HASHstringHash operator (digit if available) (#)
LOCALEstringLocale modifier ([$-1E020404])
MINUSstringMinus sign (-)
MODIFIERstringAn unidentified modifier ([Schwarz])
NATNUMstringNumber display modifier ([NatNum3])
PARENstringParenthesis character ())
PERCENTstringPercent operator (%)
PLUSstringPlus sign (+)
POINTstringDecimal point operator (.)
QMARKstringQuestion mark operator (digit or space if not available) (?)
SCALEstringScaling operator (,)
SKIPstringSkip with char operator and operand (*_)
SLASHstringSlash operator (/)
SPACEstringSpace ()
STRINGstringQuoted string ("days")
TEXTstringText output operator (@)
ZEROstringZero operator (digit or zero if not available) (0)

Types

# FormatDateInfo

An object detailing which date specifiers are used in a format pattern.

Properties
NameTypeDescription
clockType12 | 2412 if the pattern uses AM/PM clock else 24.
daybooleantrue if the pattern uses day of the month else false.
hoursbooleantrue if the pattern uses hours else false.
minutesbooleantrue if the pattern uses minutes else false.
monthbooleantrue if the pattern uses months else false.
secondsbooleantrue if the pattern uses seconds else false.
yearbooleantrue if the pattern uses years else false.

# FormatInfo

An object of information properties based on a format pattern.

Properties
NameTypeDescription
codestringCorresponds to Excel's CELL("format") functionality. It should match Excel's esoteric behaviour fairly well. See Microsoft's documentation.
color0 | 11 if the format uses color on the negative portion of the string, else a 0. This replicates Excel's CELL("color") functionality.
grouped0 | 11 if the positive portion of the format uses a thousands separator, else a 0.
isDatebooleanCorresponds to the output from isDateFormat.
isPercentbooleanCorresponds to the output from isPercentFormat.
isTextbooleanCorresponds to the output from isTextFormat.
levelnumberAn arbirarty number that represents the format's specificity if you want to compare one to another. Integer comparisons roughly match Excel's resolutions when it determines which format wins out.
maxDecimalsnumberThe maximum number of decimals this format will emit.
parentheses0 | 11 if the positive portion of the number format contains an open parenthesis, else a 0. This is replicates Excel's CELL("parentheses") functionality.
scalenumberThe multiplier used when formatting the number (100 for percentages).
type"currency" | "date" | "datetime" | "error" | "fraction" | "general" | "grouped" | "number" | "percent" | "scientific" | "text" | "time"A string identifier for the type of the number formatter.

# FormatToken

Properties
NameTypeDescription
rawstringRaw token source.
typestringToken type.
valueanyThe value of the token, cleaned of extra characters.

# LocaleData

An object of properties used by a formatter when printing a number in a certain locale.

Properties
NameTypeDescription
ampmArray<string>How AM and PM should be presented
boolArray<string>How TRUE and FALSE should be presented
dddArray<string>Shortened day names (Wed)
ddddArray<string>Long day names (Wednesday)
decimalstringSymbol used to separate integers from fractions (usually .)
exponentstringSymbol used to indicate an exponent (usually E)
groupstringSymbol used as a grouping separator (1,000,000 uses ,)
infinitystringSymbol used to indicate infinite values ()
mmmArray<string>Short month names for the Gregorian calendar (Nov)
mmm6Array<string>Short month names for the Islamic calendar (Raj.)
mmmmArray<string>Long month names for the Gregorian calendar (November)
mmmm6Array<string>Long month names for the Islamic calendar (Rajab)
nanstringSymbol used to indicate NaN values (NaN)
negativestringSymbol used to indicate positive numbers (usually -)
percentstringSymbol used to indicate a percentage (usually %)
positivestringSymbol used to indicate positive numbers (usually +)
preferMDYbooleanIs the prefered date format month first (12/31/2025) or day first (31/12/2025)

# LocaleToken

An object of properties for a locale tag.

Properties
NameTypeDescription
langstringThe basic tag such as zh_CN or fi
languagestringThe language section (zh for zh_CN)
territorystringThe territory section (CN for zh_CN)

# ParseData

Properties
NameTypeDescription
vnumber | booleanthe value
[z]stringnumber format pattern

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
numfmt/API.md at master · borgar/numfmt · GitHub
Skip to content

Latest commit

History

History
667 lines (452 loc) · 48.4 KB

File metadata and controls

667 lines (452 loc) · 48.4 KB

Numfmt API

Functions

Constant

Types

Functions

# addLocale( localeSettings, l4e ) ⇒ LocaleData

Register locale data for a language so for use when formatting.

Any partial set of properties may be returned to have the defaults used where properties are missing.

See also: {LocaleData}.

Parameters
NameTypeDefaultDescription
localeSettingsobjectA collection of settings for a locale.
localeSettings.[ampm]Array<string>["AM","PM"]How AM and PM should be presented.
localeSettings.[bool]Array<string>["TRUE", "FALSE"]How TRUE and FALSE should be presented.
localeSettings.[ddd]Array<string>["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]Shortened day names (e.g. Wed)
localeSettings.[dddd]Array<string>["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]Long day names (e.g. Wednesday)
localeSettings.[decimal]string"."Symbol used to separate integers from fractions (usually .)
localeSettings.[exponent]string"E"Symbol used to indicate an exponent (usually E)
localeSettings.[group]string"\u00a0"Symbol used as a grouping separator (1,000,000 uses ,)
localeSettings.[infinity]string"∞"Symbol used to indicate infinite values ()
localeSettings.[mmm]Array<string>["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]Short month names for the Gregorian calendar (e.g. Nov)
localeSettings.[mmm6]Array<string>["Muh.", "Saf.", "Rab. I", "Rab. II", "Jum. I", "Jum. II", "Raj.", "Sha.", "Ram.", "Shaw.", "Dhuʻl-Q.", "Dhuʻl-H."]Short month names for the Islamic calendar (e.g. Raj.)
localeSettings.[mmmm]Array<string>["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]Long month names for the Gregorian calendar (e.g. November)
localeSettings.[mmmm6]Array<string>["Muharram", "Safar", "Rabiʻ I", "Rabiʻ II", "Jumada I", "Jumada II", "Rajab", "Shaʻban", "Ramadan", "Shawwal", "Dhuʻl-Qiʻdah", "Dhuʻl-Hijjah"]Long month names for the Islamic calendar (e.g. Rajab)
localeSettings.[nan]string"NaN"Symbol used to indicate NaN values (NaN)
localeSettings.[negative]string"-"Symbol used to indicate positive numbers (usually -)
localeSettings.[percent]string"%"Symbol used to indicate a percentage (usually %)
localeSettings.[positive]string"+"Symbol used to indicate positive numbers (usually +)
localeSettings.[preferMDY]booleanfalseIs the prefered date format month first (12/31/2025) or day first (31/12/2025)
l4estringA string BCP 47 tag of the locale.
Returns

LocaleData – - A full collection of settings for a locale


# dateFromSerial( serialDate, [options = {}] ) ⇒ Array<number>

Convert a spreadsheet serial date to an array of date parts. Accurate to a second.

// output as [ Y, M, D, h, m, s ]dateFromSerial(28627);// [ 1978, 5, 17, 0, 0, 0 ]
Parameters
NameTypeDefaultDescription
serialDatenumberThe date
[options]object{}The options
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug.
Returns

Array<number> – returns an array of date parts


# dateToSerial( date, [options = {}] ) ⇒ number | null

Convert a native JavaScript Date, or array to an spreadsheet serial date.

Returns a serial date number if input was a Date object or an array of numbers, a null.

// input as DatedateToSerial(newDate(1978,5,17));// 28627// input as [ Y, M, D, h, m, s ]dateToSerial([1978,5,17]);// 28627// other inputdateToSerial("something else");// null
Parameters
NameTypeDefaultDescription
dateDate | Array<number>The date
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally time zone will be taken into account. This makes the conversion to serial date ignore the timezone offset.
Returns

number | null – The date as a spreadsheet serial date, or null.


# format( pattern, value, [options = {}] ) ⇒ string

Formats a value as a string and returns the result.

  • Dates are normalized to spreadsheet style serial dates and then formatted. - Booleans are emitted as uppercase "TRUE" or "FALSE". - Null and Undefined will return an empty string "". - Any non number values will be stringified and passed through the text section of the format pattern. - NaNs and infinites will use the corresponding strings from the active locale.
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].bigintErrorNumberbooleanfalseShould the formatter switch to a plain string number format when trying to format a bigint that is out of bounds?
[options].dateErrorNumberbooleantrueShould the formatter switch to a General number format when trying to format a date that is out of bounds?
[options].dateErrorThrowsbooleanfalseShould the formatter throw an error when trying to format a date that is out of bounds?
[options].dateSpanLargebooleantrueExtends the allowed range of dates from Excel bounds (1900–9999) to Google Sheet bounds (0–99999).
[options].fillCharboolean""When the formatter encounters * it normally emits nothing instead of the * and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].invalidstring"######"The string emitted when no-throw mode fails to parse a pattern.
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug. It is a requirement in the Ecma OOXML specification so it is on by default.
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
[options].nbspbooleanfalseBy default the output will use a regular space, but in many cases you may desire a non-breaking-space instead.
[options].overflowstring"######"The string emitted when a formatter fails to format a date that is out of bounds.
[options].skipCharboolean""When the formatter encounters _ it normally emits a single space instead of the _ and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string – A formatted value


# formatColor( pattern, value, [options = {}] ) ⇒ string | number | null

Find the color appropriate to a value as dictated by a format pattern.

If the pattern defines colors, this function will emit the color appropriate to the value. If no colors were specified this function returns undefined.

constcolor=formatColor("[green]#,##0;[red]-#,##0",-10);console.log(color);// "red"constcolor=formatColor("[green]#,##0;-#,##0",-10);console.log(color);// null
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].indexColorsbooleantrueWhen indexed color modifiers are used ([Color 1]) the formatter will convert the index into the corresponding hex color of the default palette. When this option is set to false, the number will instead by emitted allowing you to index against a custom palette.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string | number | null – A string color value as described by the pattern or a number if the indexColors option has been set to false.


# getFormatDateInfo( pattern ) ⇒ FormatDateInfo

Gets information about date codes use in a format string.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

FormatDateInfo – An object of format date properties.


# getFormatInfo( pattern, [options = {}] ) ⇒ FormatInfo

Returns an object detailing the properties and internals of a format parsed format pattern.

Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
[options]object{}Options
[options].currencystringLimit the patterns identified as currency to those that use the give string. If nothing is provided, patterns will be tagged as currency if one of the following currency symbols is used: ¤$£¥֏؋৳฿៛₡₦₩₪₫€₭₮₱₲₴₸₹₺₼₽₾₿
Returns

FormatInfo – An object of format properties.


# getLocale( locale ) ⇒ LocaleData | null

Used by the formatter to pull a locate from its registered locales. If subtag isn't available but the base language is, the base language is used. So if en-CA is not found, the formatter tries to find en else it returns a null.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale, or an Excel locale code.
Returns

LocaleData | null – - An object of format date properties.


# isDateFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a date pattern.

The pattern is considered a date pattern if any of its sections contain a date symbol (such as Y or H). Each section is restricted to be either a number or date format.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isPercentFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a percentage pattern.

The pattern is considered a percentage pattern if any of its sections contains an unescaped percentage symbol.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isTextFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a text only pattern.

The pattern is considered text only if its definition is composed of a single section that includes that text symbol (@).

For example @ or @" USD" are text patterns but #;@ is not.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isValidFormat( pattern ) ⇒ boolean

Determine if a given format pattern is valid.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is valid, False otherwise.


# parseBool( value, [options = {}] ) ⇒ ParseData | null

Parse a string input and return its boolean value. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with one property:

  • v: the parsed value.

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe supposed boolean to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseDate( value, [options = {}] ) ⇒ ParseData | null

Parse a date or datetime string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseLocale( locale ) ⇒ LocaleToken

Parse a regular IETF BCP 47 locale tag and emit an object of its parts. Irregular tags and subtags are not supported.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale.
Returns

LocaleToken – - An object describing the locale.


# parseNumber( value, [options = {}] ) ⇒ ParseData | null

Parse a numeric string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. * z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe number to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseTime( value, [options = {}] ) ⇒ ParseData | null

Parse a time string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseValue( value, [options = {}] ) ⇒ ParseData | null

Attempt to parse a "spreadsheet input" string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: The parsed value. For dates, this will be an Excel style serial date. - z: (Optionally) the number format string of the input. This property will not be present if it amounts to the General format.

parseValue() recognizes a wide range of dates and date-times, times, numbers, and booleans. Some examples:

// basic numberparseValue("-123");// { v: -123 }// formatted numberparseValue("$1,234");// { v: 1234, z: "$#,##0" }// a percentparseValue("12.3%");// { v: 0.123, z: "0.00%" }// a dateparseValue("07 October 1984");// { v: 30962, z: 'dd mmmm yyyy' }// an ISO formatted date-timeparseValue("1984-09-10 11:12:13.1234");// { v: 30935.46681855787, z: "yyyy-mm-dd hh:mm:ss" }// a booleanparseValue("false");// { v: false }

The formatting string outputted may not correspond exactly to the input. Rather, is it composed of certain elements which the input controls. This is comparable to how Microsoft Excel and Google Sheets parse pasted input. Some things you may expect:

  • Whitespace is ignored. - Decimal fractions are always represented by .00 regardless of how many digits were shown in the input. - Negatives denoted by parentheses [(1,234)] will not include the parentheses in the format string (the value will still by negative.) - All "scientific notation" returns the same format: 0.00E+00.

Internally the parser calls, parseNumber, parseDate, parseTime and parseBool. They work in the same way except with a more limited scope. You may want those function if you are limiting input to a smaller scope.

Be warned that the parser do not (yet) take locale into account so all input is assumed to be in "en-US". This means that 1,234.5 will parse, but 1.234,5 will not. Similarly, the order of date parts will be US centric. This may change in the future so be careful what options you pass the functions.

Parameters
NameTypeDefaultDescription
valuestringThe value to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# round( number, [places] ) ⇒ number

Return a number rounded to the specified amount of places. This is the rounding function used internally by the formatter (symmetric arithmetic rounding).

Parameters
NameTypeDefaultDescription
numbernumberThe number to round.
[places]number0The number of decimals to round to.
Returns

number – A rounded number.


# tokenize( pattern ) ⇒ Array<FormatToken>

Breaks a format pattern string into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: 'zero',value: '0',raw: '0'},{type: 'point',value: '.',raw: '.'},{type: 'zero',value: '0',raw: '0'},{type: 'percent',value: '%',raw: '%'}]

Token types may be found as an Object as the tokenTypes export of the package.

Parameters
NameTypeDescription
patternstringThe format pattern
Returns

Array<FormatToken> – a list of tokens


Constant

# tokenTypes = Readonly<Record<string, string>>

A dictionary of the types used to identify token variants.

See also:tokenize.

Properties
NameTypeDescription
AMPMstringAM/PM operator (AM/PM, A/P)
BREAKstringSemicolon operator indicating a break between format sections (;)
CALENDARstringCalendar modifier (B2)
CHARstringSingle non-operator character (m)
COLORstringColor modifier ([Black], [color 5])
COMMAstringPlain non-operator comma (,)
CONDITIONstringCondition modifier for a section ([>=10])
DATETIMEstringDate-time operator (mmmm, YY)
DBNUMstringNumber display modifier ([DBNum23])
DIGITstringA digit between 1 and 9 (3)
DURATIONstringTime duration ([ss])
ERRORstringUnidentifiable or illegal character (Ň)
ESCAPEDstringEscaped character (\E)
EXPstringExponent operator (E+)
FILLstringFill with char operator and operand (*_)
GENERALstringGeneral format operator (General)
GROUPstringNumber grouping operator (,)
HASHstringHash operator (digit if available) (#)
LOCALEstringLocale modifier ([$-1E020404])
MINUSstringMinus sign (-)
MODIFIERstringAn unidentified modifier ([Schwarz])
NATNUMstringNumber display modifier ([NatNum3])
PARENstringParenthesis character ())
PERCENTstringPercent operator (%)
PLUSstringPlus sign (+)
POINTstringDecimal point operator (.)
QMARKstringQuestion mark operator (digit or space if not available) (?)
SCALEstringScaling operator (,)
SKIPstringSkip with char operator and operand (*_)
SLASHstringSlash operator (/)
SPACEstringSpace ()
STRINGstringQuoted string ("days")
TEXTstringText output operator (@)
ZEROstringZero operator (digit or zero if not available) (0)

Types

# FormatDateInfo

An object detailing which date specifiers are used in a format pattern.

Properties
NameTypeDescription
clockType12 | 2412 if the pattern uses AM/PM clock else 24.
daybooleantrue if the pattern uses day of the month else false.
hoursbooleantrue if the pattern uses hours else false.
minutesbooleantrue if the pattern uses minutes else false.
monthbooleantrue if the pattern uses months else false.
secondsbooleantrue if the pattern uses seconds else false.
yearbooleantrue if the pattern uses years else false.

# FormatInfo

An object of information properties based on a format pattern.

Properties
NameTypeDescription
codestringCorresponds to Excel's CELL("format") functionality. It should match Excel's esoteric behaviour fairly well. See Microsoft's documentation.
color0 | 11 if the format uses color on the negative portion of the string, else a 0. This replicates Excel's CELL("color") functionality.
grouped0 | 11 if the positive portion of the format uses a thousands separator, else a 0.
isDatebooleanCorresponds to the output from isDateFormat.
isPercentbooleanCorresponds to the output from isPercentFormat.
isTextbooleanCorresponds to the output from isTextFormat.
levelnumberAn arbirarty number that represents the format's specificity if you want to compare one to another. Integer comparisons roughly match Excel's resolutions when it determines which format wins out.
maxDecimalsnumberThe maximum number of decimals this format will emit.
parentheses0 | 11 if the positive portion of the number format contains an open parenthesis, else a 0. This is replicates Excel's CELL("parentheses") functionality.
scalenumberThe multiplier used when formatting the number (100 for percentages).
type"currency" | "date" | "datetime" | "error" | "fraction" | "general" | "grouped" | "number" | "percent" | "scientific" | "text" | "time"A string identifier for the type of the number formatter.

# FormatToken

Properties
NameTypeDescription
rawstringRaw token source.
typestringToken type.
valueanyThe value of the token, cleaned of extra characters.

# LocaleData

An object of properties used by a formatter when printing a number in a certain locale.

Properties
NameTypeDescription
ampmArray<string>How AM and PM should be presented
boolArray<string>How TRUE and FALSE should be presented
dddArray<string>Shortened day names (Wed)
ddddArray<string>Long day names (Wednesday)
decimalstringSymbol used to separate integers from fractions (usually .)
exponentstringSymbol used to indicate an exponent (usually E)
groupstringSymbol used as a grouping separator (1,000,000 uses ,)
infinitystringSymbol used to indicate infinite values ()
mmmArray<string>Short month names for the Gregorian calendar (Nov)
mmm6Array<string>Short month names for the Islamic calendar (Raj.)
mmmmArray<string>Long month names for the Gregorian calendar (November)
mmmm6Array<string>Long month names for the Islamic calendar (Rajab)
nanstringSymbol used to indicate NaN values (NaN)
negativestringSymbol used to indicate positive numbers (usually -)
percentstringSymbol used to indicate a percentage (usually %)
positivestringSymbol used to indicate positive numbers (usually +)
preferMDYbooleanIs the prefered date format month first (12/31/2025) or day first (31/12/2025)

# LocaleToken

An object of properties for a locale tag.

Properties
NameTypeDescription
langstringThe basic tag such as zh_CN or fi
languagestringThe language section (zh for zh_CN)
territorystringThe territory section (CN for zh_CN)

# ParseData

Properties
NameTypeDescription
vnumber | booleanthe value
[z]stringnumber format pattern

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' numfmt/API.md at master · borgar/numfmt · GitHub
Skip to content

Latest commit

History

History
667 lines (452 loc) · 48.4 KB

File metadata and controls

667 lines (452 loc) · 48.4 KB

Numfmt API

Functions

Constant

Types

Functions

# addLocale( localeSettings, l4e ) ⇒ LocaleData

Register locale data for a language so for use when formatting.

Any partial set of properties may be returned to have the defaults used where properties are missing.

See also: {LocaleData}.

Parameters
NameTypeDefaultDescription
localeSettingsobjectA collection of settings for a locale.
localeSettings.[ampm]Array<string>["AM","PM"]How AM and PM should be presented.
localeSettings.[bool]Array<string>["TRUE", "FALSE"]How TRUE and FALSE should be presented.
localeSettings.[ddd]Array<string>["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]Shortened day names (e.g. Wed)
localeSettings.[dddd]Array<string>["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]Long day names (e.g. Wednesday)
localeSettings.[decimal]string"."Symbol used to separate integers from fractions (usually .)
localeSettings.[exponent]string"E"Symbol used to indicate an exponent (usually E)
localeSettings.[group]string"\u00a0"Symbol used as a grouping separator (1,000,000 uses ,)
localeSettings.[infinity]string"∞"Symbol used to indicate infinite values ()
localeSettings.[mmm]Array<string>["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]Short month names for the Gregorian calendar (e.g. Nov)
localeSettings.[mmm6]Array<string>["Muh.", "Saf.", "Rab. I", "Rab. II", "Jum. I", "Jum. II", "Raj.", "Sha.", "Ram.", "Shaw.", "Dhuʻl-Q.", "Dhuʻl-H."]Short month names for the Islamic calendar (e.g. Raj.)
localeSettings.[mmmm]Array<string>["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]Long month names for the Gregorian calendar (e.g. November)
localeSettings.[mmmm6]Array<string>["Muharram", "Safar", "Rabiʻ I", "Rabiʻ II", "Jumada I", "Jumada II", "Rajab", "Shaʻban", "Ramadan", "Shawwal", "Dhuʻl-Qiʻdah", "Dhuʻl-Hijjah"]Long month names for the Islamic calendar (e.g. Rajab)
localeSettings.[nan]string"NaN"Symbol used to indicate NaN values (NaN)
localeSettings.[negative]string"-"Symbol used to indicate positive numbers (usually -)
localeSettings.[percent]string"%"Symbol used to indicate a percentage (usually %)
localeSettings.[positive]string"+"Symbol used to indicate positive numbers (usually +)
localeSettings.[preferMDY]booleanfalseIs the prefered date format month first (12/31/2025) or day first (31/12/2025)
l4estringA string BCP 47 tag of the locale.
Returns

LocaleData – - A full collection of settings for a locale


# dateFromSerial( serialDate, [options = {}] ) ⇒ Array<number>

Convert a spreadsheet serial date to an array of date parts. Accurate to a second.

// output as [ Y, M, D, h, m, s ]dateFromSerial(28627);// [ 1978, 5, 17, 0, 0, 0 ]
Parameters
NameTypeDefaultDescription
serialDatenumberThe date
[options]object{}The options
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug.
Returns

Array<number> – returns an array of date parts


# dateToSerial( date, [options = {}] ) ⇒ number | null

Convert a native JavaScript Date, or array to an spreadsheet serial date.

Returns a serial date number if input was a Date object or an array of numbers, a null.

// input as DatedateToSerial(newDate(1978,5,17));// 28627// input as [ Y, M, D, h, m, s ]dateToSerial([1978,5,17]);// 28627// other inputdateToSerial("something else");// null
Parameters
NameTypeDefaultDescription
dateDate | Array<number>The date
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally time zone will be taken into account. This makes the conversion to serial date ignore the timezone offset.
Returns

number | null – The date as a spreadsheet serial date, or null.


# format( pattern, value, [options = {}] ) ⇒ string

Formats a value as a string and returns the result.

  • Dates are normalized to spreadsheet style serial dates and then formatted. - Booleans are emitted as uppercase "TRUE" or "FALSE". - Null and Undefined will return an empty string "". - Any non number values will be stringified and passed through the text section of the format pattern. - NaNs and infinites will use the corresponding strings from the active locale.
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].bigintErrorNumberbooleanfalseShould the formatter switch to a plain string number format when trying to format a bigint that is out of bounds?
[options].dateErrorNumberbooleantrueShould the formatter switch to a General number format when trying to format a date that is out of bounds?
[options].dateErrorThrowsbooleanfalseShould the formatter throw an error when trying to format a date that is out of bounds?
[options].dateSpanLargebooleantrueExtends the allowed range of dates from Excel bounds (1900–9999) to Google Sheet bounds (0–99999).
[options].fillCharboolean""When the formatter encounters * it normally emits nothing instead of the * and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].invalidstring"######"The string emitted when no-throw mode fails to parse a pattern.
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug. It is a requirement in the Ecma OOXML specification so it is on by default.
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
[options].nbspbooleanfalseBy default the output will use a regular space, but in many cases you may desire a non-breaking-space instead.
[options].overflowstring"######"The string emitted when a formatter fails to format a date that is out of bounds.
[options].skipCharboolean""When the formatter encounters _ it normally emits a single space instead of the _ and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string – A formatted value


# formatColor( pattern, value, [options = {}] ) ⇒ string | number | null

Find the color appropriate to a value as dictated by a format pattern.

If the pattern defines colors, this function will emit the color appropriate to the value. If no colors were specified this function returns undefined.

constcolor=formatColor("[green]#,##0;[red]-#,##0",-10);console.log(color);// "red"constcolor=formatColor("[green]#,##0;-#,##0",-10);console.log(color);// null
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].indexColorsbooleantrueWhen indexed color modifiers are used ([Color 1]) the formatter will convert the index into the corresponding hex color of the default palette. When this option is set to false, the number will instead by emitted allowing you to index against a custom palette.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string | number | null – A string color value as described by the pattern or a number if the indexColors option has been set to false.


# getFormatDateInfo( pattern ) ⇒ FormatDateInfo

Gets information about date codes use in a format string.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

FormatDateInfo – An object of format date properties.


# getFormatInfo( pattern, [options = {}] ) ⇒ FormatInfo

Returns an object detailing the properties and internals of a format parsed format pattern.

Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
[options]object{}Options
[options].currencystringLimit the patterns identified as currency to those that use the give string. If nothing is provided, patterns will be tagged as currency if one of the following currency symbols is used: ¤$£¥֏؋৳฿៛₡₦₩₪₫€₭₮₱₲₴₸₹₺₼₽₾₿
Returns

FormatInfo – An object of format properties.


# getLocale( locale ) ⇒ LocaleData | null

Used by the formatter to pull a locate from its registered locales. If subtag isn't available but the base language is, the base language is used. So if en-CA is not found, the formatter tries to find en else it returns a null.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale, or an Excel locale code.
Returns

LocaleData | null – - An object of format date properties.


# isDateFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a date pattern.

The pattern is considered a date pattern if any of its sections contain a date symbol (such as Y or H). Each section is restricted to be either a number or date format.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isPercentFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a percentage pattern.

The pattern is considered a percentage pattern if any of its sections contains an unescaped percentage symbol.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isTextFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a text only pattern.

The pattern is considered text only if its definition is composed of a single section that includes that text symbol (@).

For example @ or @" USD" are text patterns but #;@ is not.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isValidFormat( pattern ) ⇒ boolean

Determine if a given format pattern is valid.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is valid, False otherwise.


# parseBool( value, [options = {}] ) ⇒ ParseData | null

Parse a string input and return its boolean value. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with one property:

  • v: the parsed value.

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe supposed boolean to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseDate( value, [options = {}] ) ⇒ ParseData | null

Parse a date or datetime string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseLocale( locale ) ⇒ LocaleToken

Parse a regular IETF BCP 47 locale tag and emit an object of its parts. Irregular tags and subtags are not supported.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale.
Returns

LocaleToken – - An object describing the locale.


# parseNumber( value, [options = {}] ) ⇒ ParseData | null

Parse a numeric string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. * z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe number to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseTime( value, [options = {}] ) ⇒ ParseData | null

Parse a time string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseValue( value, [options = {}] ) ⇒ ParseData | null

Attempt to parse a "spreadsheet input" string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: The parsed value. For dates, this will be an Excel style serial date. - z: (Optionally) the number format string of the input. This property will not be present if it amounts to the General format.

parseValue() recognizes a wide range of dates and date-times, times, numbers, and booleans. Some examples:

// basic numberparseValue("-123");// { v: -123 }// formatted numberparseValue("$1,234");// { v: 1234, z: "$#,##0" }// a percentparseValue("12.3%");// { v: 0.123, z: "0.00%" }// a dateparseValue("07 October 1984");// { v: 30962, z: 'dd mmmm yyyy' }// an ISO formatted date-timeparseValue("1984-09-10 11:12:13.1234");// { v: 30935.46681855787, z: "yyyy-mm-dd hh:mm:ss" }// a booleanparseValue("false");// { v: false }

The formatting string outputted may not correspond exactly to the input. Rather, is it composed of certain elements which the input controls. This is comparable to how Microsoft Excel and Google Sheets parse pasted input. Some things you may expect:

  • Whitespace is ignored. - Decimal fractions are always represented by .00 regardless of how many digits were shown in the input. - Negatives denoted by parentheses [(1,234)] will not include the parentheses in the format string (the value will still by negative.) - All "scientific notation" returns the same format: 0.00E+00.

Internally the parser calls, parseNumber, parseDate, parseTime and parseBool. They work in the same way except with a more limited scope. You may want those function if you are limiting input to a smaller scope.

Be warned that the parser do not (yet) take locale into account so all input is assumed to be in "en-US". This means that 1,234.5 will parse, but 1.234,5 will not. Similarly, the order of date parts will be US centric. This may change in the future so be careful what options you pass the functions.

Parameters
NameTypeDefaultDescription
valuestringThe value to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# round( number, [places] ) ⇒ number

Return a number rounded to the specified amount of places. This is the rounding function used internally by the formatter (symmetric arithmetic rounding).

Parameters
NameTypeDefaultDescription
numbernumberThe number to round.
[places]number0The number of decimals to round to.
Returns

number – A rounded number.


# tokenize( pattern ) ⇒ Array<FormatToken>

Breaks a format pattern string into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: 'zero',value: '0',raw: '0'},{type: 'point',value: '.',raw: '.'},{type: 'zero',value: '0',raw: '0'},{type: 'percent',value: '%',raw: '%'}]

Token types may be found as an Object as the tokenTypes export of the package.

Parameters
NameTypeDescription
patternstringThe format pattern
Returns

Array<FormatToken> – a list of tokens


Constant

# tokenTypes = Readonly<Record<string, string>>

A dictionary of the types used to identify token variants.

See also:tokenize.

Properties
NameTypeDescription
AMPMstringAM/PM operator (AM/PM, A/P)
BREAKstringSemicolon operator indicating a break between format sections (;)
CALENDARstringCalendar modifier (B2)
CHARstringSingle non-operator character (m)
COLORstringColor modifier ([Black], [color 5])
COMMAstringPlain non-operator comma (,)
CONDITIONstringCondition modifier for a section ([>=10])
DATETIMEstringDate-time operator (mmmm, YY)
DBNUMstringNumber display modifier ([DBNum23])
DIGITstringA digit between 1 and 9 (3)
DURATIONstringTime duration ([ss])
ERRORstringUnidentifiable or illegal character (Ň)
ESCAPEDstringEscaped character (\E)
EXPstringExponent operator (E+)
FILLstringFill with char operator and operand (*_)
GENERALstringGeneral format operator (General)
GROUPstringNumber grouping operator (,)
HASHstringHash operator (digit if available) (#)
LOCALEstringLocale modifier ([$-1E020404])
MINUSstringMinus sign (-)
MODIFIERstringAn unidentified modifier ([Schwarz])
NATNUMstringNumber display modifier ([NatNum3])
PARENstringParenthesis character ())
PERCENTstringPercent operator (%)
PLUSstringPlus sign (+)
POINTstringDecimal point operator (.)
QMARKstringQuestion mark operator (digit or space if not available) (?)
SCALEstringScaling operator (,)
SKIPstringSkip with char operator and operand (*_)
SLASHstringSlash operator (/)
SPACEstringSpace ()
STRINGstringQuoted string ("days")
TEXTstringText output operator (@)
ZEROstringZero operator (digit or zero if not available) (0)

Types

# FormatDateInfo

An object detailing which date specifiers are used in a format pattern.

Properties
NameTypeDescription
clockType12 | 2412 if the pattern uses AM/PM clock else 24.
daybooleantrue if the pattern uses day of the month else false.
hoursbooleantrue if the pattern uses hours else false.
minutesbooleantrue if the pattern uses minutes else false.
monthbooleantrue if the pattern uses months else false.
secondsbooleantrue if the pattern uses seconds else false.
yearbooleantrue if the pattern uses years else false.

# FormatInfo

An object of information properties based on a format pattern.

Properties
NameTypeDescription
codestringCorresponds to Excel's CELL("format") functionality. It should match Excel's esoteric behaviour fairly well. See Microsoft's documentation.
color0 | 11 if the format uses color on the negative portion of the string, else a 0. This replicates Excel's CELL("color") functionality.
grouped0 | 11 if the positive portion of the format uses a thousands separator, else a 0.
isDatebooleanCorresponds to the output from isDateFormat.
isPercentbooleanCorresponds to the output from isPercentFormat.
isTextbooleanCorresponds to the output from isTextFormat.
levelnumberAn arbirarty number that represents the format's specificity if you want to compare one to another. Integer comparisons roughly match Excel's resolutions when it determines which format wins out.
maxDecimalsnumberThe maximum number of decimals this format will emit.
parentheses0 | 11 if the positive portion of the number format contains an open parenthesis, else a 0. This is replicates Excel's CELL("parentheses") functionality.
scalenumberThe multiplier used when formatting the number (100 for percentages).
type"currency" | "date" | "datetime" | "error" | "fraction" | "general" | "grouped" | "number" | "percent" | "scientific" | "text" | "time"A string identifier for the type of the number formatter.

# FormatToken

Properties
NameTypeDescription
rawstringRaw token source.
typestringToken type.
valueanyThe value of the token, cleaned of extra characters.

# LocaleData

An object of properties used by a formatter when printing a number in a certain locale.

Properties
NameTypeDescription
ampmArray<string>How AM and PM should be presented
boolArray<string>How TRUE and FALSE should be presented
dddArray<string>Shortened day names (Wed)
ddddArray<string>Long day names (Wednesday)
decimalstringSymbol used to separate integers from fractions (usually .)
exponentstringSymbol used to indicate an exponent (usually E)
groupstringSymbol used as a grouping separator (1,000,000 uses ,)
infinitystringSymbol used to indicate infinite values ()
mmmArray<string>Short month names for the Gregorian calendar (Nov)
mmm6Array<string>Short month names for the Islamic calendar (Raj.)
mmmmArray<string>Long month names for the Gregorian calendar (November)
mmmm6Array<string>Long month names for the Islamic calendar (Rajab)
nanstringSymbol used to indicate NaN values (NaN)
negativestringSymbol used to indicate positive numbers (usually -)
percentstringSymbol used to indicate a percentage (usually %)
positivestringSymbol used to indicate positive numbers (usually +)
preferMDYbooleanIs the prefered date format month first (12/31/2025) or day first (31/12/2025)

# LocaleToken

An object of properties for a locale tag.

Properties
NameTypeDescription
langstringThe basic tag such as zh_CN or fi
languagestringThe language section (zh for zh_CN)
territorystringThe territory section (CN for zh_CN)

# ParseData

Properties
NameTypeDescription
vnumber | booleanthe value
[z]stringnumber format pattern

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' numfmt/API.md at master · borgar/numfmt · GitHub
Skip to content

Latest commit

History

History
667 lines (452 loc) · 48.4 KB

File metadata and controls

667 lines (452 loc) · 48.4 KB

Numfmt API

Functions

Constant

Types

Functions

# addLocale( localeSettings, l4e ) ⇒ LocaleData

Register locale data for a language so for use when formatting.

Any partial set of properties may be returned to have the defaults used where properties are missing.

See also: {LocaleData}.

Parameters
NameTypeDefaultDescription
localeSettingsobjectA collection of settings for a locale.
localeSettings.[ampm]Array<string>["AM","PM"]How AM and PM should be presented.
localeSettings.[bool]Array<string>["TRUE", "FALSE"]How TRUE and FALSE should be presented.
localeSettings.[ddd]Array<string>["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]Shortened day names (e.g. Wed)
localeSettings.[dddd]Array<string>["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]Long day names (e.g. Wednesday)
localeSettings.[decimal]string"."Symbol used to separate integers from fractions (usually .)
localeSettings.[exponent]string"E"Symbol used to indicate an exponent (usually E)
localeSettings.[group]string"\u00a0"Symbol used as a grouping separator (1,000,000 uses ,)
localeSettings.[infinity]string"∞"Symbol used to indicate infinite values ()
localeSettings.[mmm]Array<string>["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]Short month names for the Gregorian calendar (e.g. Nov)
localeSettings.[mmm6]Array<string>["Muh.", "Saf.", "Rab. I", "Rab. II", "Jum. I", "Jum. II", "Raj.", "Sha.", "Ram.", "Shaw.", "Dhuʻl-Q.", "Dhuʻl-H."]Short month names for the Islamic calendar (e.g. Raj.)
localeSettings.[mmmm]Array<string>["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]Long month names for the Gregorian calendar (e.g. November)
localeSettings.[mmmm6]Array<string>["Muharram", "Safar", "Rabiʻ I", "Rabiʻ II", "Jumada I", "Jumada II", "Rajab", "Shaʻban", "Ramadan", "Shawwal", "Dhuʻl-Qiʻdah", "Dhuʻl-Hijjah"]Long month names for the Islamic calendar (e.g. Rajab)
localeSettings.[nan]string"NaN"Symbol used to indicate NaN values (NaN)
localeSettings.[negative]string"-"Symbol used to indicate positive numbers (usually -)
localeSettings.[percent]string"%"Symbol used to indicate a percentage (usually %)
localeSettings.[positive]string"+"Symbol used to indicate positive numbers (usually +)
localeSettings.[preferMDY]booleanfalseIs the prefered date format month first (12/31/2025) or day first (31/12/2025)
l4estringA string BCP 47 tag of the locale.
Returns

LocaleData – - A full collection of settings for a locale


# dateFromSerial( serialDate, [options = {}] ) ⇒ Array<number>

Convert a spreadsheet serial date to an array of date parts. Accurate to a second.

// output as [ Y, M, D, h, m, s ]dateFromSerial(28627);// [ 1978, 5, 17, 0, 0, 0 ]
Parameters
NameTypeDefaultDescription
serialDatenumberThe date
[options]object{}The options
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug.
Returns

Array<number> – returns an array of date parts


# dateToSerial( date, [options = {}] ) ⇒ number | null

Convert a native JavaScript Date, or array to an spreadsheet serial date.

Returns a serial date number if input was a Date object or an array of numbers, a null.

// input as DatedateToSerial(newDate(1978,5,17));// 28627// input as [ Y, M, D, h, m, s ]dateToSerial([1978,5,17]);// 28627// other inputdateToSerial("something else");// null
Parameters
NameTypeDefaultDescription
dateDate | Array<number>The date
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally time zone will be taken into account. This makes the conversion to serial date ignore the timezone offset.
Returns

number | null – The date as a spreadsheet serial date, or null.


# format( pattern, value, [options = {}] ) ⇒ string

Formats a value as a string and returns the result.

  • Dates are normalized to spreadsheet style serial dates and then formatted. - Booleans are emitted as uppercase "TRUE" or "FALSE". - Null and Undefined will return an empty string "". - Any non number values will be stringified and passed through the text section of the format pattern. - NaNs and infinites will use the corresponding strings from the active locale.
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].bigintErrorNumberbooleanfalseShould the formatter switch to a plain string number format when trying to format a bigint that is out of bounds?
[options].dateErrorNumberbooleantrueShould the formatter switch to a General number format when trying to format a date that is out of bounds?
[options].dateErrorThrowsbooleanfalseShould the formatter throw an error when trying to format a date that is out of bounds?
[options].dateSpanLargebooleantrueExtends the allowed range of dates from Excel bounds (1900–9999) to Google Sheet bounds (0–99999).
[options].fillCharboolean""When the formatter encounters * it normally emits nothing instead of the * and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].invalidstring"######"The string emitted when no-throw mode fails to parse a pattern.
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug. It is a requirement in the Ecma OOXML specification so it is on by default.
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
[options].nbspbooleanfalseBy default the output will use a regular space, but in many cases you may desire a non-breaking-space instead.
[options].overflowstring"######"The string emitted when a formatter fails to format a date that is out of bounds.
[options].skipCharboolean""When the formatter encounters _ it normally emits a single space instead of the _ and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string – A formatted value


# formatColor( pattern, value, [options = {}] ) ⇒ string | number | null

Find the color appropriate to a value as dictated by a format pattern.

If the pattern defines colors, this function will emit the color appropriate to the value. If no colors were specified this function returns undefined.

constcolor=formatColor("[green]#,##0;[red]-#,##0",-10);console.log(color);// "red"constcolor=formatColor("[green]#,##0;-#,##0",-10);console.log(color);// null
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].indexColorsbooleantrueWhen indexed color modifiers are used ([Color 1]) the formatter will convert the index into the corresponding hex color of the default palette. When this option is set to false, the number will instead by emitted allowing you to index against a custom palette.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string | number | null – A string color value as described by the pattern or a number if the indexColors option has been set to false.


# getFormatDateInfo( pattern ) ⇒ FormatDateInfo

Gets information about date codes use in a format string.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

FormatDateInfo – An object of format date properties.


# getFormatInfo( pattern, [options = {}] ) ⇒ FormatInfo

Returns an object detailing the properties and internals of a format parsed format pattern.

Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
[options]object{}Options
[options].currencystringLimit the patterns identified as currency to those that use the give string. If nothing is provided, patterns will be tagged as currency if one of the following currency symbols is used: ¤$£¥֏؋৳฿៛₡₦₩₪₫€₭₮₱₲₴₸₹₺₼₽₾₿
Returns

FormatInfo – An object of format properties.


# getLocale( locale ) ⇒ LocaleData | null

Used by the formatter to pull a locate from its registered locales. If subtag isn't available but the base language is, the base language is used. So if en-CA is not found, the formatter tries to find en else it returns a null.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale, or an Excel locale code.
Returns

LocaleData | null – - An object of format date properties.


# isDateFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a date pattern.

The pattern is considered a date pattern if any of its sections contain a date symbol (such as Y or H). Each section is restricted to be either a number or date format.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isPercentFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a percentage pattern.

The pattern is considered a percentage pattern if any of its sections contains an unescaped percentage symbol.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isTextFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a text only pattern.

The pattern is considered text only if its definition is composed of a single section that includes that text symbol (@).

For example @ or @" USD" are text patterns but #;@ is not.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isValidFormat( pattern ) ⇒ boolean

Determine if a given format pattern is valid.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is valid, False otherwise.


# parseBool( value, [options = {}] ) ⇒ ParseData | null

Parse a string input and return its boolean value. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with one property:

  • v: the parsed value.

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe supposed boolean to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseDate( value, [options = {}] ) ⇒ ParseData | null

Parse a date or datetime string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseLocale( locale ) ⇒ LocaleToken

Parse a regular IETF BCP 47 locale tag and emit an object of its parts. Irregular tags and subtags are not supported.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale.
Returns

LocaleToken – - An object describing the locale.


# parseNumber( value, [options = {}] ) ⇒ ParseData | null

Parse a numeric string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. * z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe number to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseTime( value, [options = {}] ) ⇒ ParseData | null

Parse a time string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseValue( value, [options = {}] ) ⇒ ParseData | null

Attempt to parse a "spreadsheet input" string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: The parsed value. For dates, this will be an Excel style serial date. - z: (Optionally) the number format string of the input. This property will not be present if it amounts to the General format.

parseValue() recognizes a wide range of dates and date-times, times, numbers, and booleans. Some examples:

// basic numberparseValue("-123");// { v: -123 }// formatted numberparseValue("$1,234");// { v: 1234, z: "$#,##0" }// a percentparseValue("12.3%");// { v: 0.123, z: "0.00%" }// a dateparseValue("07 October 1984");// { v: 30962, z: 'dd mmmm yyyy' }// an ISO formatted date-timeparseValue("1984-09-10 11:12:13.1234");// { v: 30935.46681855787, z: "yyyy-mm-dd hh:mm:ss" }// a booleanparseValue("false");// { v: false }

The formatting string outputted may not correspond exactly to the input. Rather, is it composed of certain elements which the input controls. This is comparable to how Microsoft Excel and Google Sheets parse pasted input. Some things you may expect:

  • Whitespace is ignored. - Decimal fractions are always represented by .00 regardless of how many digits were shown in the input. - Negatives denoted by parentheses [(1,234)] will not include the parentheses in the format string (the value will still by negative.) - All "scientific notation" returns the same format: 0.00E+00.

Internally the parser calls, parseNumber, parseDate, parseTime and parseBool. They work in the same way except with a more limited scope. You may want those function if you are limiting input to a smaller scope.

Be warned that the parser do not (yet) take locale into account so all input is assumed to be in "en-US". This means that 1,234.5 will parse, but 1.234,5 will not. Similarly, the order of date parts will be US centric. This may change in the future so be careful what options you pass the functions.

Parameters
NameTypeDefaultDescription
valuestringThe value to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# round( number, [places] ) ⇒ number

Return a number rounded to the specified amount of places. This is the rounding function used internally by the formatter (symmetric arithmetic rounding).

Parameters
NameTypeDefaultDescription
numbernumberThe number to round.
[places]number0The number of decimals to round to.
Returns

number – A rounded number.


# tokenize( pattern ) ⇒ Array<FormatToken>

Breaks a format pattern string into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: 'zero',value: '0',raw: '0'},{type: 'point',value: '.',raw: '.'},{type: 'zero',value: '0',raw: '0'},{type: 'percent',value: '%',raw: '%'}]

Token types may be found as an Object as the tokenTypes export of the package.

Parameters
NameTypeDescription
patternstringThe format pattern
Returns

Array<FormatToken> – a list of tokens


Constant

# tokenTypes = Readonly<Record<string, string>>

A dictionary of the types used to identify token variants.

See also:tokenize.

Properties
NameTypeDescription
AMPMstringAM/PM operator (AM/PM, A/P)
BREAKstringSemicolon operator indicating a break between format sections (;)
CALENDARstringCalendar modifier (B2)
CHARstringSingle non-operator character (m)
COLORstringColor modifier ([Black], [color 5])
COMMAstringPlain non-operator comma (,)
CONDITIONstringCondition modifier for a section ([>=10])
DATETIMEstringDate-time operator (mmmm, YY)
DBNUMstringNumber display modifier ([DBNum23])
DIGITstringA digit between 1 and 9 (3)
DURATIONstringTime duration ([ss])
ERRORstringUnidentifiable or illegal character (Ň)
ESCAPEDstringEscaped character (\E)
EXPstringExponent operator (E+)
FILLstringFill with char operator and operand (*_)
GENERALstringGeneral format operator (General)
GROUPstringNumber grouping operator (,)
HASHstringHash operator (digit if available) (#)
LOCALEstringLocale modifier ([$-1E020404])
MINUSstringMinus sign (-)
MODIFIERstringAn unidentified modifier ([Schwarz])
NATNUMstringNumber display modifier ([NatNum3])
PARENstringParenthesis character ())
PERCENTstringPercent operator (%)
PLUSstringPlus sign (+)
POINTstringDecimal point operator (.)
QMARKstringQuestion mark operator (digit or space if not available) (?)
SCALEstringScaling operator (,)
SKIPstringSkip with char operator and operand (*_)
SLASHstringSlash operator (/)
SPACEstringSpace ()
STRINGstringQuoted string ("days")
TEXTstringText output operator (@)
ZEROstringZero operator (digit or zero if not available) (0)

Types

# FormatDateInfo

An object detailing which date specifiers are used in a format pattern.

Properties
NameTypeDescription
clockType12 | 2412 if the pattern uses AM/PM clock else 24.
daybooleantrue if the pattern uses day of the month else false.
hoursbooleantrue if the pattern uses hours else false.
minutesbooleantrue if the pattern uses minutes else false.
monthbooleantrue if the pattern uses months else false.
secondsbooleantrue if the pattern uses seconds else false.
yearbooleantrue if the pattern uses years else false.

# FormatInfo

An object of information properties based on a format pattern.

Properties
NameTypeDescription
codestringCorresponds to Excel's CELL("format") functionality. It should match Excel's esoteric behaviour fairly well. See Microsoft's documentation.
color0 | 11 if the format uses color on the negative portion of the string, else a 0. This replicates Excel's CELL("color") functionality.
grouped0 | 11 if the positive portion of the format uses a thousands separator, else a 0.
isDatebooleanCorresponds to the output from isDateFormat.
isPercentbooleanCorresponds to the output from isPercentFormat.
isTextbooleanCorresponds to the output from isTextFormat.
levelnumberAn arbirarty number that represents the format's specificity if you want to compare one to another. Integer comparisons roughly match Excel's resolutions when it determines which format wins out.
maxDecimalsnumberThe maximum number of decimals this format will emit.
parentheses0 | 11 if the positive portion of the number format contains an open parenthesis, else a 0. This is replicates Excel's CELL("parentheses") functionality.
scalenumberThe multiplier used when formatting the number (100 for percentages).
type"currency" | "date" | "datetime" | "error" | "fraction" | "general" | "grouped" | "number" | "percent" | "scientific" | "text" | "time"A string identifier for the type of the number formatter.

# FormatToken

Properties
NameTypeDescription
rawstringRaw token source.
typestringToken type.
valueanyThe value of the token, cleaned of extra characters.

# LocaleData

An object of properties used by a formatter when printing a number in a certain locale.

Properties
NameTypeDescription
ampmArray<string>How AM and PM should be presented
boolArray<string>How TRUE and FALSE should be presented
dddArray<string>Shortened day names (Wed)
ddddArray<string>Long day names (Wednesday)
decimalstringSymbol used to separate integers from fractions (usually .)
exponentstringSymbol used to indicate an exponent (usually E)
groupstringSymbol used as a grouping separator (1,000,000 uses ,)
infinitystringSymbol used to indicate infinite values ()
mmmArray<string>Short month names for the Gregorian calendar (Nov)
mmm6Array<string>Short month names for the Islamic calendar (Raj.)
mmmmArray<string>Long month names for the Gregorian calendar (November)
mmmm6Array<string>Long month names for the Islamic calendar (Rajab)
nanstringSymbol used to indicate NaN values (NaN)
negativestringSymbol used to indicate positive numbers (usually -)
percentstringSymbol used to indicate a percentage (usually %)
positivestringSymbol used to indicate positive numbers (usually +)
preferMDYbooleanIs the prefered date format month first (12/31/2025) or day first (31/12/2025)

# LocaleToken

An object of properties for a locale tag.

Properties
NameTypeDescription
langstringThe basic tag such as zh_CN or fi
languagestringThe language section (zh for zh_CN)
territorystringThe territory section (CN for zh_CN)

# ParseData

Properties
NameTypeDescription
vnumber | booleanthe value
[z]stringnumber format pattern

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' numfmt/API.md at master · borgar/numfmt · GitHub
Skip to content

Latest commit

History

History
667 lines (452 loc) · 48.4 KB

File metadata and controls

667 lines (452 loc) · 48.4 KB

Numfmt API

Functions

Constant

Types

Functions

# addLocale( localeSettings, l4e ) ⇒ LocaleData

Register locale data for a language so for use when formatting.

Any partial set of properties may be returned to have the defaults used where properties are missing.

See also: {LocaleData}.

Parameters
NameTypeDefaultDescription
localeSettingsobjectA collection of settings for a locale.
localeSettings.[ampm]Array<string>["AM","PM"]How AM and PM should be presented.
localeSettings.[bool]Array<string>["TRUE", "FALSE"]How TRUE and FALSE should be presented.
localeSettings.[ddd]Array<string>["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]Shortened day names (e.g. Wed)
localeSettings.[dddd]Array<string>["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]Long day names (e.g. Wednesday)
localeSettings.[decimal]string"."Symbol used to separate integers from fractions (usually .)
localeSettings.[exponent]string"E"Symbol used to indicate an exponent (usually E)
localeSettings.[group]string"\u00a0"Symbol used as a grouping separator (1,000,000 uses ,)
localeSettings.[infinity]string"∞"Symbol used to indicate infinite values ()
localeSettings.[mmm]Array<string>["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]Short month names for the Gregorian calendar (e.g. Nov)
localeSettings.[mmm6]Array<string>["Muh.", "Saf.", "Rab. I", "Rab. II", "Jum. I", "Jum. II", "Raj.", "Sha.", "Ram.", "Shaw.", "Dhuʻl-Q.", "Dhuʻl-H."]Short month names for the Islamic calendar (e.g. Raj.)
localeSettings.[mmmm]Array<string>["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]Long month names for the Gregorian calendar (e.g. November)
localeSettings.[mmmm6]Array<string>["Muharram", "Safar", "Rabiʻ I", "Rabiʻ II", "Jumada I", "Jumada II", "Rajab", "Shaʻban", "Ramadan", "Shawwal", "Dhuʻl-Qiʻdah", "Dhuʻl-Hijjah"]Long month names for the Islamic calendar (e.g. Rajab)
localeSettings.[nan]string"NaN"Symbol used to indicate NaN values (NaN)
localeSettings.[negative]string"-"Symbol used to indicate positive numbers (usually -)
localeSettings.[percent]string"%"Symbol used to indicate a percentage (usually %)
localeSettings.[positive]string"+"Symbol used to indicate positive numbers (usually +)
localeSettings.[preferMDY]booleanfalseIs the prefered date format month first (12/31/2025) or day first (31/12/2025)
l4estringA string BCP 47 tag of the locale.
Returns

LocaleData – - A full collection of settings for a locale


# dateFromSerial( serialDate, [options = {}] ) ⇒ Array<number>

Convert a spreadsheet serial date to an array of date parts. Accurate to a second.

// output as [ Y, M, D, h, m, s ]dateFromSerial(28627);// [ 1978, 5, 17, 0, 0, 0 ]
Parameters
NameTypeDefaultDescription
serialDatenumberThe date
[options]object{}The options
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug.
Returns

Array<number> – returns an array of date parts


# dateToSerial( date, [options = {}] ) ⇒ number | null

Convert a native JavaScript Date, or array to an spreadsheet serial date.

Returns a serial date number if input was a Date object or an array of numbers, a null.

// input as DatedateToSerial(newDate(1978,5,17));// 28627// input as [ Y, M, D, h, m, s ]dateToSerial([1978,5,17]);// 28627// other inputdateToSerial("something else");// null
Parameters
NameTypeDefaultDescription
dateDate | Array<number>The date
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally time zone will be taken into account. This makes the conversion to serial date ignore the timezone offset.
Returns

number | null – The date as a spreadsheet serial date, or null.


# format( pattern, value, [options = {}] ) ⇒ string

Formats a value as a string and returns the result.

  • Dates are normalized to spreadsheet style serial dates and then formatted. - Booleans are emitted as uppercase "TRUE" or "FALSE". - Null and Undefined will return an empty string "". - Any non number values will be stringified and passed through the text section of the format pattern. - NaNs and infinites will use the corresponding strings from the active locale.
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].bigintErrorNumberbooleanfalseShould the formatter switch to a plain string number format when trying to format a bigint that is out of bounds?
[options].dateErrorNumberbooleantrueShould the formatter switch to a General number format when trying to format a date that is out of bounds?
[options].dateErrorThrowsbooleanfalseShould the formatter throw an error when trying to format a date that is out of bounds?
[options].dateSpanLargebooleantrueExtends the allowed range of dates from Excel bounds (1900–9999) to Google Sheet bounds (0–99999).
[options].fillCharboolean""When the formatter encounters * it normally emits nothing instead of the * and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].invalidstring"######"The string emitted when no-throw mode fails to parse a pattern.
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug. It is a requirement in the Ecma OOXML specification so it is on by default.
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
[options].nbspbooleanfalseBy default the output will use a regular space, but in many cases you may desire a non-breaking-space instead.
[options].overflowstring"######"The string emitted when a formatter fails to format a date that is out of bounds.
[options].skipCharboolean""When the formatter encounters _ it normally emits a single space instead of the _ and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string – A formatted value


# formatColor( pattern, value, [options = {}] ) ⇒ string | number | null

Find the color appropriate to a value as dictated by a format pattern.

If the pattern defines colors, this function will emit the color appropriate to the value. If no colors were specified this function returns undefined.

constcolor=formatColor("[green]#,##0;[red]-#,##0",-10);console.log(color);// "red"constcolor=formatColor("[green]#,##0;-#,##0",-10);console.log(color);// null
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].indexColorsbooleantrueWhen indexed color modifiers are used ([Color 1]) the formatter will convert the index into the corresponding hex color of the default palette. When this option is set to false, the number will instead by emitted allowing you to index against a custom palette.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string | number | null – A string color value as described by the pattern or a number if the indexColors option has been set to false.


# getFormatDateInfo( pattern ) ⇒ FormatDateInfo

Gets information about date codes use in a format string.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

FormatDateInfo – An object of format date properties.


# getFormatInfo( pattern, [options = {}] ) ⇒ FormatInfo

Returns an object detailing the properties and internals of a format parsed format pattern.

Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
[options]object{}Options
[options].currencystringLimit the patterns identified as currency to those that use the give string. If nothing is provided, patterns will be tagged as currency if one of the following currency symbols is used: ¤$£¥֏؋৳฿៛₡₦₩₪₫€₭₮₱₲₴₸₹₺₼₽₾₿
Returns

FormatInfo – An object of format properties.


# getLocale( locale ) ⇒ LocaleData | null

Used by the formatter to pull a locate from its registered locales. If subtag isn't available but the base language is, the base language is used. So if en-CA is not found, the formatter tries to find en else it returns a null.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale, or an Excel locale code.
Returns

LocaleData | null – - An object of format date properties.


# isDateFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a date pattern.

The pattern is considered a date pattern if any of its sections contain a date symbol (such as Y or H). Each section is restricted to be either a number or date format.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isPercentFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a percentage pattern.

The pattern is considered a percentage pattern if any of its sections contains an unescaped percentage symbol.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isTextFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a text only pattern.

The pattern is considered text only if its definition is composed of a single section that includes that text symbol (@).

For example @ or @" USD" are text patterns but #;@ is not.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isValidFormat( pattern ) ⇒ boolean

Determine if a given format pattern is valid.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is valid, False otherwise.


# parseBool( value, [options = {}] ) ⇒ ParseData | null

Parse a string input and return its boolean value. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with one property:

  • v: the parsed value.

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe supposed boolean to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseDate( value, [options = {}] ) ⇒ ParseData | null

Parse a date or datetime string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseLocale( locale ) ⇒ LocaleToken

Parse a regular IETF BCP 47 locale tag and emit an object of its parts. Irregular tags and subtags are not supported.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale.
Returns

LocaleToken – - An object describing the locale.


# parseNumber( value, [options = {}] ) ⇒ ParseData | null

Parse a numeric string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. * z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe number to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseTime( value, [options = {}] ) ⇒ ParseData | null

Parse a time string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseValue( value, [options = {}] ) ⇒ ParseData | null

Attempt to parse a "spreadsheet input" string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: The parsed value. For dates, this will be an Excel style serial date. - z: (Optionally) the number format string of the input. This property will not be present if it amounts to the General format.

parseValue() recognizes a wide range of dates and date-times, times, numbers, and booleans. Some examples:

// basic numberparseValue("-123");// { v: -123 }// formatted numberparseValue("$1,234");// { v: 1234, z: "$#,##0" }// a percentparseValue("12.3%");// { v: 0.123, z: "0.00%" }// a dateparseValue("07 October 1984");// { v: 30962, z: 'dd mmmm yyyy' }// an ISO formatted date-timeparseValue("1984-09-10 11:12:13.1234");// { v: 30935.46681855787, z: "yyyy-mm-dd hh:mm:ss" }// a booleanparseValue("false");// { v: false }

The formatting string outputted may not correspond exactly to the input. Rather, is it composed of certain elements which the input controls. This is comparable to how Microsoft Excel and Google Sheets parse pasted input. Some things you may expect:

  • Whitespace is ignored. - Decimal fractions are always represented by .00 regardless of how many digits were shown in the input. - Negatives denoted by parentheses [(1,234)] will not include the parentheses in the format string (the value will still by negative.) - All "scientific notation" returns the same format: 0.00E+00.

Internally the parser calls, parseNumber, parseDate, parseTime and parseBool. They work in the same way except with a more limited scope. You may want those function if you are limiting input to a smaller scope.

Be warned that the parser do not (yet) take locale into account so all input is assumed to be in "en-US". This means that 1,234.5 will parse, but 1.234,5 will not. Similarly, the order of date parts will be US centric. This may change in the future so be careful what options you pass the functions.

Parameters
NameTypeDefaultDescription
valuestringThe value to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# round( number, [places] ) ⇒ number

Return a number rounded to the specified amount of places. This is the rounding function used internally by the formatter (symmetric arithmetic rounding).

Parameters
NameTypeDefaultDescription
numbernumberThe number to round.
[places]number0The number of decimals to round to.
Returns

number – A rounded number.


# tokenize( pattern ) ⇒ Array<FormatToken>

Breaks a format pattern string into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: 'zero',value: '0',raw: '0'},{type: 'point',value: '.',raw: '.'},{type: 'zero',value: '0',raw: '0'},{type: 'percent',value: '%',raw: '%'}]

Token types may be found as an Object as the tokenTypes export of the package.

Parameters
NameTypeDescription
patternstringThe format pattern
Returns

Array<FormatToken> – a list of tokens


Constant

# tokenTypes = Readonly<Record<string, string>>

A dictionary of the types used to identify token variants.

See also:tokenize.

Properties
NameTypeDescription
AMPMstringAM/PM operator (AM/PM, A/P)
BREAKstringSemicolon operator indicating a break between format sections (;)
CALENDARstringCalendar modifier (B2)
CHARstringSingle non-operator character (m)
COLORstringColor modifier ([Black], [color 5])
COMMAstringPlain non-operator comma (,)
CONDITIONstringCondition modifier for a section ([>=10])
DATETIMEstringDate-time operator (mmmm, YY)
DBNUMstringNumber display modifier ([DBNum23])
DIGITstringA digit between 1 and 9 (3)
DURATIONstringTime duration ([ss])
ERRORstringUnidentifiable or illegal character (Ň)
ESCAPEDstringEscaped character (\E)
EXPstringExponent operator (E+)
FILLstringFill with char operator and operand (*_)
GENERALstringGeneral format operator (General)
GROUPstringNumber grouping operator (,)
HASHstringHash operator (digit if available) (#)
LOCALEstringLocale modifier ([$-1E020404])
MINUSstringMinus sign (-)
MODIFIERstringAn unidentified modifier ([Schwarz])
NATNUMstringNumber display modifier ([NatNum3])
PARENstringParenthesis character ())
PERCENTstringPercent operator (%)
PLUSstringPlus sign (+)
POINTstringDecimal point operator (.)
QMARKstringQuestion mark operator (digit or space if not available) (?)
SCALEstringScaling operator (,)
SKIPstringSkip with char operator and operand (*_)
SLASHstringSlash operator (/)
SPACEstringSpace ()
STRINGstringQuoted string ("days")
TEXTstringText output operator (@)
ZEROstringZero operator (digit or zero if not available) (0)

Types

# FormatDateInfo

An object detailing which date specifiers are used in a format pattern.

Properties
NameTypeDescription
clockType12 | 2412 if the pattern uses AM/PM clock else 24.
daybooleantrue if the pattern uses day of the month else false.
hoursbooleantrue if the pattern uses hours else false.
minutesbooleantrue if the pattern uses minutes else false.
monthbooleantrue if the pattern uses months else false.
secondsbooleantrue if the pattern uses seconds else false.
yearbooleantrue if the pattern uses years else false.

# FormatInfo

An object of information properties based on a format pattern.

Properties
NameTypeDescription
codestringCorresponds to Excel's CELL("format") functionality. It should match Excel's esoteric behaviour fairly well. See Microsoft's documentation.
color0 | 11 if the format uses color on the negative portion of the string, else a 0. This replicates Excel's CELL("color") functionality.
grouped0 | 11 if the positive portion of the format uses a thousands separator, else a 0.
isDatebooleanCorresponds to the output from isDateFormat.
isPercentbooleanCorresponds to the output from isPercentFormat.
isTextbooleanCorresponds to the output from isTextFormat.
levelnumberAn arbirarty number that represents the format's specificity if you want to compare one to another. Integer comparisons roughly match Excel's resolutions when it determines which format wins out.
maxDecimalsnumberThe maximum number of decimals this format will emit.
parentheses0 | 11 if the positive portion of the number format contains an open parenthesis, else a 0. This is replicates Excel's CELL("parentheses") functionality.
scalenumberThe multiplier used when formatting the number (100 for percentages).
type"currency" | "date" | "datetime" | "error" | "fraction" | "general" | "grouped" | "number" | "percent" | "scientific" | "text" | "time"A string identifier for the type of the number formatter.

# FormatToken

Properties
NameTypeDescription
rawstringRaw token source.
typestringToken type.
valueanyThe value of the token, cleaned of extra characters.

# LocaleData

An object of properties used by a formatter when printing a number in a certain locale.

Properties
NameTypeDescription
ampmArray<string>How AM and PM should be presented
boolArray<string>How TRUE and FALSE should be presented
dddArray<string>Shortened day names (Wed)
ddddArray<string>Long day names (Wednesday)
decimalstringSymbol used to separate integers from fractions (usually .)
exponentstringSymbol used to indicate an exponent (usually E)
groupstringSymbol used as a grouping separator (1,000,000 uses ,)
infinitystringSymbol used to indicate infinite values ()
mmmArray<string>Short month names for the Gregorian calendar (Nov)
mmm6Array<string>Short month names for the Islamic calendar (Raj.)
mmmmArray<string>Long month names for the Gregorian calendar (November)
mmmm6Array<string>Long month names for the Islamic calendar (Rajab)
nanstringSymbol used to indicate NaN values (NaN)
negativestringSymbol used to indicate positive numbers (usually -)
percentstringSymbol used to indicate a percentage (usually %)
positivestringSymbol used to indicate positive numbers (usually +)
preferMDYbooleanIs the prefered date format month first (12/31/2025) or day first (31/12/2025)

# LocaleToken

An object of properties for a locale tag.

Properties
NameTypeDescription
langstringThe basic tag such as zh_CN or fi
languagestringThe language section (zh for zh_CN)
territorystringThe territory section (CN for zh_CN)

# ParseData

Properties
NameTypeDescription
vnumber | booleanthe value
[z]stringnumber format pattern

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' numfmt/API.md at master · borgar/numfmt · GitHub
Skip to content

Latest commit

History

History
667 lines (452 loc) · 48.4 KB

File metadata and controls

667 lines (452 loc) · 48.4 KB

Numfmt API

Functions

Constant

Types

Functions

# addLocale( localeSettings, l4e ) ⇒ LocaleData

Register locale data for a language so for use when formatting.

Any partial set of properties may be returned to have the defaults used where properties are missing.

See also: {LocaleData}.

Parameters
NameTypeDefaultDescription
localeSettingsobjectA collection of settings for a locale.
localeSettings.[ampm]Array<string>["AM","PM"]How AM and PM should be presented.
localeSettings.[bool]Array<string>["TRUE", "FALSE"]How TRUE and FALSE should be presented.
localeSettings.[ddd]Array<string>["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]Shortened day names (e.g. Wed)
localeSettings.[dddd]Array<string>["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]Long day names (e.g. Wednesday)
localeSettings.[decimal]string"."Symbol used to separate integers from fractions (usually .)
localeSettings.[exponent]string"E"Symbol used to indicate an exponent (usually E)
localeSettings.[group]string"\u00a0"Symbol used as a grouping separator (1,000,000 uses ,)
localeSettings.[infinity]string"∞"Symbol used to indicate infinite values ()
localeSettings.[mmm]Array<string>["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]Short month names for the Gregorian calendar (e.g. Nov)
localeSettings.[mmm6]Array<string>["Muh.", "Saf.", "Rab. I", "Rab. II", "Jum. I", "Jum. II", "Raj.", "Sha.", "Ram.", "Shaw.", "Dhuʻl-Q.", "Dhuʻl-H."]Short month names for the Islamic calendar (e.g. Raj.)
localeSettings.[mmmm]Array<string>["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]Long month names for the Gregorian calendar (e.g. November)
localeSettings.[mmmm6]Array<string>["Muharram", "Safar", "Rabiʻ I", "Rabiʻ II", "Jumada I", "Jumada II", "Rajab", "Shaʻban", "Ramadan", "Shawwal", "Dhuʻl-Qiʻdah", "Dhuʻl-Hijjah"]Long month names for the Islamic calendar (e.g. Rajab)
localeSettings.[nan]string"NaN"Symbol used to indicate NaN values (NaN)
localeSettings.[negative]string"-"Symbol used to indicate positive numbers (usually -)
localeSettings.[percent]string"%"Symbol used to indicate a percentage (usually %)
localeSettings.[positive]string"+"Symbol used to indicate positive numbers (usually +)
localeSettings.[preferMDY]booleanfalseIs the prefered date format month first (12/31/2025) or day first (31/12/2025)
l4estringA string BCP 47 tag of the locale.
Returns

LocaleData – - A full collection of settings for a locale


# dateFromSerial( serialDate, [options = {}] ) ⇒ Array<number>

Convert a spreadsheet serial date to an array of date parts. Accurate to a second.

// output as [ Y, M, D, h, m, s ]dateFromSerial(28627);// [ 1978, 5, 17, 0, 0, 0 ]
Parameters
NameTypeDefaultDescription
serialDatenumberThe date
[options]object{}The options
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug.
Returns

Array<number> – returns an array of date parts


# dateToSerial( date, [options = {}] ) ⇒ number | null

Convert a native JavaScript Date, or array to an spreadsheet serial date.

Returns a serial date number if input was a Date object or an array of numbers, a null.

// input as DatedateToSerial(newDate(1978,5,17));// 28627// input as [ Y, M, D, h, m, s ]dateToSerial([1978,5,17]);// 28627// other inputdateToSerial("something else");// null
Parameters
NameTypeDefaultDescription
dateDate | Array<number>The date
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally time zone will be taken into account. This makes the conversion to serial date ignore the timezone offset.
Returns

number | null – The date as a spreadsheet serial date, or null.


# format( pattern, value, [options = {}] ) ⇒ string

Formats a value as a string and returns the result.

  • Dates are normalized to spreadsheet style serial dates and then formatted. - Booleans are emitted as uppercase "TRUE" or "FALSE". - Null and Undefined will return an empty string "". - Any non number values will be stringified and passed through the text section of the format pattern. - NaNs and infinites will use the corresponding strings from the active locale.
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].bigintErrorNumberbooleanfalseShould the formatter switch to a plain string number format when trying to format a bigint that is out of bounds?
[options].dateErrorNumberbooleantrueShould the formatter switch to a General number format when trying to format a date that is out of bounds?
[options].dateErrorThrowsbooleanfalseShould the formatter throw an error when trying to format a date that is out of bounds?
[options].dateSpanLargebooleantrueExtends the allowed range of dates from Excel bounds (1900–9999) to Google Sheet bounds (0–99999).
[options].fillCharboolean""When the formatter encounters * it normally emits nothing instead of the * and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].invalidstring"######"The string emitted when no-throw mode fails to parse a pattern.
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug. It is a requirement in the Ecma OOXML specification so it is on by default.
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
[options].nbspbooleanfalseBy default the output will use a regular space, but in many cases you may desire a non-breaking-space instead.
[options].overflowstring"######"The string emitted when a formatter fails to format a date that is out of bounds.
[options].skipCharboolean""When the formatter encounters _ it normally emits a single space instead of the _ and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string – A formatted value


# formatColor( pattern, value, [options = {}] ) ⇒ string | number | null

Find the color appropriate to a value as dictated by a format pattern.

If the pattern defines colors, this function will emit the color appropriate to the value. If no colors were specified this function returns undefined.

constcolor=formatColor("[green]#,##0;[red]-#,##0",-10);console.log(color);// "red"constcolor=formatColor("[green]#,##0;-#,##0",-10);console.log(color);// null
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].indexColorsbooleantrueWhen indexed color modifiers are used ([Color 1]) the formatter will convert the index into the corresponding hex color of the default palette. When this option is set to false, the number will instead by emitted allowing you to index against a custom palette.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string | number | null – A string color value as described by the pattern or a number if the indexColors option has been set to false.


# getFormatDateInfo( pattern ) ⇒ FormatDateInfo

Gets information about date codes use in a format string.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

FormatDateInfo – An object of format date properties.


# getFormatInfo( pattern, [options = {}] ) ⇒ FormatInfo

Returns an object detailing the properties and internals of a format parsed format pattern.

Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
[options]object{}Options
[options].currencystringLimit the patterns identified as currency to those that use the give string. If nothing is provided, patterns will be tagged as currency if one of the following currency symbols is used: ¤$£¥֏؋৳฿៛₡₦₩₪₫€₭₮₱₲₴₸₹₺₼₽₾₿
Returns

FormatInfo – An object of format properties.


# getLocale( locale ) ⇒ LocaleData | null

Used by the formatter to pull a locate from its registered locales. If subtag isn't available but the base language is, the base language is used. So if en-CA is not found, the formatter tries to find en else it returns a null.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale, or an Excel locale code.
Returns

LocaleData | null – - An object of format date properties.


# isDateFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a date pattern.

The pattern is considered a date pattern if any of its sections contain a date symbol (such as Y or H). Each section is restricted to be either a number or date format.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isPercentFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a percentage pattern.

The pattern is considered a percentage pattern if any of its sections contains an unescaped percentage symbol.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isTextFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a text only pattern.

The pattern is considered text only if its definition is composed of a single section that includes that text symbol (@).

For example @ or @" USD" are text patterns but #;@ is not.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isValidFormat( pattern ) ⇒ boolean

Determine if a given format pattern is valid.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is valid, False otherwise.


# parseBool( value, [options = {}] ) ⇒ ParseData | null

Parse a string input and return its boolean value. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with one property:

  • v: the parsed value.

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe supposed boolean to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseDate( value, [options = {}] ) ⇒ ParseData | null

Parse a date or datetime string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseLocale( locale ) ⇒ LocaleToken

Parse a regular IETF BCP 47 locale tag and emit an object of its parts. Irregular tags and subtags are not supported.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale.
Returns

LocaleToken – - An object describing the locale.


# parseNumber( value, [options = {}] ) ⇒ ParseData | null

Parse a numeric string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. * z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe number to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseTime( value, [options = {}] ) ⇒ ParseData | null

Parse a time string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseValue( value, [options = {}] ) ⇒ ParseData | null

Attempt to parse a "spreadsheet input" string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: The parsed value. For dates, this will be an Excel style serial date. - z: (Optionally) the number format string of the input. This property will not be present if it amounts to the General format.

parseValue() recognizes a wide range of dates and date-times, times, numbers, and booleans. Some examples:

// basic numberparseValue("-123");// { v: -123 }// formatted numberparseValue("$1,234");// { v: 1234, z: "$#,##0" }// a percentparseValue("12.3%");// { v: 0.123, z: "0.00%" }// a dateparseValue("07 October 1984");// { v: 30962, z: 'dd mmmm yyyy' }// an ISO formatted date-timeparseValue("1984-09-10 11:12:13.1234");// { v: 30935.46681855787, z: "yyyy-mm-dd hh:mm:ss" }// a booleanparseValue("false");// { v: false }

The formatting string outputted may not correspond exactly to the input. Rather, is it composed of certain elements which the input controls. This is comparable to how Microsoft Excel and Google Sheets parse pasted input. Some things you may expect:

  • Whitespace is ignored. - Decimal fractions are always represented by .00 regardless of how many digits were shown in the input. - Negatives denoted by parentheses [(1,234)] will not include the parentheses in the format string (the value will still by negative.) - All "scientific notation" returns the same format: 0.00E+00.

Internally the parser calls, parseNumber, parseDate, parseTime and parseBool. They work in the same way except with a more limited scope. You may want those function if you are limiting input to a smaller scope.

Be warned that the parser do not (yet) take locale into account so all input is assumed to be in "en-US". This means that 1,234.5 will parse, but 1.234,5 will not. Similarly, the order of date parts will be US centric. This may change in the future so be careful what options you pass the functions.

Parameters
NameTypeDefaultDescription
valuestringThe value to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# round( number, [places] ) ⇒ number

Return a number rounded to the specified amount of places. This is the rounding function used internally by the formatter (symmetric arithmetic rounding).

Parameters
NameTypeDefaultDescription
numbernumberThe number to round.
[places]number0The number of decimals to round to.
Returns

number – A rounded number.


# tokenize( pattern ) ⇒ Array<FormatToken>

Breaks a format pattern string into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: 'zero',value: '0',raw: '0'},{type: 'point',value: '.',raw: '.'},{type: 'zero',value: '0',raw: '0'},{type: 'percent',value: '%',raw: '%'}]

Token types may be found as an Object as the tokenTypes export of the package.

Parameters
NameTypeDescription
patternstringThe format pattern
Returns

Array<FormatToken> – a list of tokens


Constant

# tokenTypes = Readonly<Record<string, string>>

A dictionary of the types used to identify token variants.

See also:tokenize.

Properties
NameTypeDescription
AMPMstringAM/PM operator (AM/PM, A/P)
BREAKstringSemicolon operator indicating a break between format sections (;)
CALENDARstringCalendar modifier (B2)
CHARstringSingle non-operator character (m)
COLORstringColor modifier ([Black], [color 5])
COMMAstringPlain non-operator comma (,)
CONDITIONstringCondition modifier for a section ([>=10])
DATETIMEstringDate-time operator (mmmm, YY)
DBNUMstringNumber display modifier ([DBNum23])
DIGITstringA digit between 1 and 9 (3)
DURATIONstringTime duration ([ss])
ERRORstringUnidentifiable or illegal character (Ň)
ESCAPEDstringEscaped character (\E)
EXPstringExponent operator (E+)
FILLstringFill with char operator and operand (*_)
GENERALstringGeneral format operator (General)
GROUPstringNumber grouping operator (,)
HASHstringHash operator (digit if available) (#)
LOCALEstringLocale modifier ([$-1E020404])
MINUSstringMinus sign (-)
MODIFIERstringAn unidentified modifier ([Schwarz])
NATNUMstringNumber display modifier ([NatNum3])
PARENstringParenthesis character ())
PERCENTstringPercent operator (%)
PLUSstringPlus sign (+)
POINTstringDecimal point operator (.)
QMARKstringQuestion mark operator (digit or space if not available) (?)
SCALEstringScaling operator (,)
SKIPstringSkip with char operator and operand (*_)
SLASHstringSlash operator (/)
SPACEstringSpace ()
STRINGstringQuoted string ("days")
TEXTstringText output operator (@)
ZEROstringZero operator (digit or zero if not available) (0)

Types

# FormatDateInfo

An object detailing which date specifiers are used in a format pattern.

Properties
NameTypeDescription
clockType12 | 2412 if the pattern uses AM/PM clock else 24.
daybooleantrue if the pattern uses day of the month else false.
hoursbooleantrue if the pattern uses hours else false.
minutesbooleantrue if the pattern uses minutes else false.
monthbooleantrue if the pattern uses months else false.
secondsbooleantrue if the pattern uses seconds else false.
yearbooleantrue if the pattern uses years else false.

# FormatInfo

An object of information properties based on a format pattern.

Properties
NameTypeDescription
codestringCorresponds to Excel's CELL("format") functionality. It should match Excel's esoteric behaviour fairly well. See Microsoft's documentation.
color0 | 11 if the format uses color on the negative portion of the string, else a 0. This replicates Excel's CELL("color") functionality.
grouped0 | 11 if the positive portion of the format uses a thousands separator, else a 0.
isDatebooleanCorresponds to the output from isDateFormat.
isPercentbooleanCorresponds to the output from isPercentFormat.
isTextbooleanCorresponds to the output from isTextFormat.
levelnumberAn arbirarty number that represents the format's specificity if you want to compare one to another. Integer comparisons roughly match Excel's resolutions when it determines which format wins out.
maxDecimalsnumberThe maximum number of decimals this format will emit.
parentheses0 | 11 if the positive portion of the number format contains an open parenthesis, else a 0. This is replicates Excel's CELL("parentheses") functionality.
scalenumberThe multiplier used when formatting the number (100 for percentages).
type"currency" | "date" | "datetime" | "error" | "fraction" | "general" | "grouped" | "number" | "percent" | "scientific" | "text" | "time"A string identifier for the type of the number formatter.

# FormatToken

Properties
NameTypeDescription
rawstringRaw token source.
typestringToken type.
valueanyThe value of the token, cleaned of extra characters.

# LocaleData

An object of properties used by a formatter when printing a number in a certain locale.

Properties
NameTypeDescription
ampmArray<string>How AM and PM should be presented
boolArray<string>How TRUE and FALSE should be presented
dddArray<string>Shortened day names (Wed)
ddddArray<string>Long day names (Wednesday)
decimalstringSymbol used to separate integers from fractions (usually .)
exponentstringSymbol used to indicate an exponent (usually E)
groupstringSymbol used as a grouping separator (1,000,000 uses ,)
infinitystringSymbol used to indicate infinite values ()
mmmArray<string>Short month names for the Gregorian calendar (Nov)
mmm6Array<string>Short month names for the Islamic calendar (Raj.)
mmmmArray<string>Long month names for the Gregorian calendar (November)
mmmm6Array<string>Long month names for the Islamic calendar (Rajab)
nanstringSymbol used to indicate NaN values (NaN)
negativestringSymbol used to indicate positive numbers (usually -)
percentstringSymbol used to indicate a percentage (usually %)
positivestringSymbol used to indicate positive numbers (usually +)
preferMDYbooleanIs the prefered date format month first (12/31/2025) or day first (31/12/2025)

# LocaleToken

An object of properties for a locale tag.

Properties
NameTypeDescription
langstringThe basic tag such as zh_CN or fi
languagestringThe language section (zh for zh_CN)
territorystringThe territory section (CN for zh_CN)

# ParseData

Properties
NameTypeDescription
vnumber | booleanthe value
[z]stringnumber format pattern

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' numfmt/API.md at master · borgar/numfmt · GitHub
Skip to content

Latest commit

History

History
667 lines (452 loc) · 48.4 KB

File metadata and controls

667 lines (452 loc) · 48.4 KB

Numfmt API

Functions

Constant

Types

Functions

# addLocale( localeSettings, l4e ) ⇒ LocaleData

Register locale data for a language so for use when formatting.

Any partial set of properties may be returned to have the defaults used where properties are missing.

See also: {LocaleData}.

Parameters
NameTypeDefaultDescription
localeSettingsobjectA collection of settings for a locale.
localeSettings.[ampm]Array<string>["AM","PM"]How AM and PM should be presented.
localeSettings.[bool]Array<string>["TRUE", "FALSE"]How TRUE and FALSE should be presented.
localeSettings.[ddd]Array<string>["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]Shortened day names (e.g. Wed)
localeSettings.[dddd]Array<string>["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]Long day names (e.g. Wednesday)
localeSettings.[decimal]string"."Symbol used to separate integers from fractions (usually .)
localeSettings.[exponent]string"E"Symbol used to indicate an exponent (usually E)
localeSettings.[group]string"\u00a0"Symbol used as a grouping separator (1,000,000 uses ,)
localeSettings.[infinity]string"∞"Symbol used to indicate infinite values ()
localeSettings.[mmm]Array<string>["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]Short month names for the Gregorian calendar (e.g. Nov)
localeSettings.[mmm6]Array<string>["Muh.", "Saf.", "Rab. I", "Rab. II", "Jum. I", "Jum. II", "Raj.", "Sha.", "Ram.", "Shaw.", "Dhuʻl-Q.", "Dhuʻl-H."]Short month names for the Islamic calendar (e.g. Raj.)
localeSettings.[mmmm]Array<string>["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]Long month names for the Gregorian calendar (e.g. November)
localeSettings.[mmmm6]Array<string>["Muharram", "Safar", "Rabiʻ I", "Rabiʻ II", "Jumada I", "Jumada II", "Rajab", "Shaʻban", "Ramadan", "Shawwal", "Dhuʻl-Qiʻdah", "Dhuʻl-Hijjah"]Long month names for the Islamic calendar (e.g. Rajab)
localeSettings.[nan]string"NaN"Symbol used to indicate NaN values (NaN)
localeSettings.[negative]string"-"Symbol used to indicate positive numbers (usually -)
localeSettings.[percent]string"%"Symbol used to indicate a percentage (usually %)
localeSettings.[positive]string"+"Symbol used to indicate positive numbers (usually +)
localeSettings.[preferMDY]booleanfalseIs the prefered date format month first (12/31/2025) or day first (31/12/2025)
l4estringA string BCP 47 tag of the locale.
Returns

LocaleData – - A full collection of settings for a locale


# dateFromSerial( serialDate, [options = {}] ) ⇒ Array<number>

Convert a spreadsheet serial date to an array of date parts. Accurate to a second.

// output as [ Y, M, D, h, m, s ]dateFromSerial(28627);// [ 1978, 5, 17, 0, 0, 0 ]
Parameters
NameTypeDefaultDescription
serialDatenumberThe date
[options]object{}The options
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug.
Returns

Array<number> – returns an array of date parts


# dateToSerial( date, [options = {}] ) ⇒ number | null

Convert a native JavaScript Date, or array to an spreadsheet serial date.

Returns a serial date number if input was a Date object or an array of numbers, a null.

// input as DatedateToSerial(newDate(1978,5,17));// 28627// input as [ Y, M, D, h, m, s ]dateToSerial([1978,5,17]);// 28627// other inputdateToSerial("something else");// null
Parameters
NameTypeDefaultDescription
dateDate | Array<number>The date
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally time zone will be taken into account. This makes the conversion to serial date ignore the timezone offset.
Returns

number | null – The date as a spreadsheet serial date, or null.


# format( pattern, value, [options = {}] ) ⇒ string

Formats a value as a string and returns the result.

  • Dates are normalized to spreadsheet style serial dates and then formatted. - Booleans are emitted as uppercase "TRUE" or "FALSE". - Null and Undefined will return an empty string "". - Any non number values will be stringified and passed through the text section of the format pattern. - NaNs and infinites will use the corresponding strings from the active locale.
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].bigintErrorNumberbooleanfalseShould the formatter switch to a plain string number format when trying to format a bigint that is out of bounds?
[options].dateErrorNumberbooleantrueShould the formatter switch to a General number format when trying to format a date that is out of bounds?
[options].dateErrorThrowsbooleanfalseShould the formatter throw an error when trying to format a date that is out of bounds?
[options].dateSpanLargebooleantrueExtends the allowed range of dates from Excel bounds (1900–9999) to Google Sheet bounds (0–99999).
[options].fillCharboolean""When the formatter encounters * it normally emits nothing instead of the * and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].invalidstring"######"The string emitted when no-throw mode fails to parse a pattern.
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug. It is a requirement in the Ecma OOXML specification so it is on by default.
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
[options].nbspbooleanfalseBy default the output will use a regular space, but in many cases you may desire a non-breaking-space instead.
[options].overflowstring"######"The string emitted when a formatter fails to format a date that is out of bounds.
[options].skipCharboolean""When the formatter encounters _ it normally emits a single space instead of the _ and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string – A formatted value


# formatColor( pattern, value, [options = {}] ) ⇒ string | number | null

Find the color appropriate to a value as dictated by a format pattern.

If the pattern defines colors, this function will emit the color appropriate to the value. If no colors were specified this function returns undefined.

constcolor=formatColor("[green]#,##0;[red]-#,##0",-10);console.log(color);// "red"constcolor=formatColor("[green]#,##0;-#,##0",-10);console.log(color);// null
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].indexColorsbooleantrueWhen indexed color modifiers are used ([Color 1]) the formatter will convert the index into the corresponding hex color of the default palette. When this option is set to false, the number will instead by emitted allowing you to index against a custom palette.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string | number | null – A string color value as described by the pattern or a number if the indexColors option has been set to false.


# getFormatDateInfo( pattern ) ⇒ FormatDateInfo

Gets information about date codes use in a format string.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

FormatDateInfo – An object of format date properties.


# getFormatInfo( pattern, [options = {}] ) ⇒ FormatInfo

Returns an object detailing the properties and internals of a format parsed format pattern.

Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
[options]object{}Options
[options].currencystringLimit the patterns identified as currency to those that use the give string. If nothing is provided, patterns will be tagged as currency if one of the following currency symbols is used: ¤$£¥֏؋৳฿៛₡₦₩₪₫€₭₮₱₲₴₸₹₺₼₽₾₿
Returns

FormatInfo – An object of format properties.


# getLocale( locale ) ⇒ LocaleData | null

Used by the formatter to pull a locate from its registered locales. If subtag isn't available but the base language is, the base language is used. So if en-CA is not found, the formatter tries to find en else it returns a null.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale, or an Excel locale code.
Returns

LocaleData | null – - An object of format date properties.


# isDateFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a date pattern.

The pattern is considered a date pattern if any of its sections contain a date symbol (such as Y or H). Each section is restricted to be either a number or date format.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isPercentFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a percentage pattern.

The pattern is considered a percentage pattern if any of its sections contains an unescaped percentage symbol.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isTextFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a text only pattern.

The pattern is considered text only if its definition is composed of a single section that includes that text symbol (@).

For example @ or @" USD" are text patterns but #;@ is not.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isValidFormat( pattern ) ⇒ boolean

Determine if a given format pattern is valid.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is valid, False otherwise.


# parseBool( value, [options = {}] ) ⇒ ParseData | null

Parse a string input and return its boolean value. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with one property:

  • v: the parsed value.

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe supposed boolean to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseDate( value, [options = {}] ) ⇒ ParseData | null

Parse a date or datetime string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseLocale( locale ) ⇒ LocaleToken

Parse a regular IETF BCP 47 locale tag and emit an object of its parts. Irregular tags and subtags are not supported.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale.
Returns

LocaleToken – - An object describing the locale.


# parseNumber( value, [options = {}] ) ⇒ ParseData | null

Parse a numeric string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. * z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe number to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseTime( value, [options = {}] ) ⇒ ParseData | null

Parse a time string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseValue( value, [options = {}] ) ⇒ ParseData | null

Attempt to parse a "spreadsheet input" string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: The parsed value. For dates, this will be an Excel style serial date. - z: (Optionally) the number format string of the input. This property will not be present if it amounts to the General format.

parseValue() recognizes a wide range of dates and date-times, times, numbers, and booleans. Some examples:

// basic numberparseValue("-123");// { v: -123 }// formatted numberparseValue("$1,234");// { v: 1234, z: "$#,##0" }// a percentparseValue("12.3%");// { v: 0.123, z: "0.00%" }// a dateparseValue("07 October 1984");// { v: 30962, z: 'dd mmmm yyyy' }// an ISO formatted date-timeparseValue("1984-09-10 11:12:13.1234");// { v: 30935.46681855787, z: "yyyy-mm-dd hh:mm:ss" }// a booleanparseValue("false");// { v: false }

The formatting string outputted may not correspond exactly to the input. Rather, is it composed of certain elements which the input controls. This is comparable to how Microsoft Excel and Google Sheets parse pasted input. Some things you may expect:

  • Whitespace is ignored. - Decimal fractions are always represented by .00 regardless of how many digits were shown in the input. - Negatives denoted by parentheses [(1,234)] will not include the parentheses in the format string (the value will still by negative.) - All "scientific notation" returns the same format: 0.00E+00.

Internally the parser calls, parseNumber, parseDate, parseTime and parseBool. They work in the same way except with a more limited scope. You may want those function if you are limiting input to a smaller scope.

Be warned that the parser do not (yet) take locale into account so all input is assumed to be in "en-US". This means that 1,234.5 will parse, but 1.234,5 will not. Similarly, the order of date parts will be US centric. This may change in the future so be careful what options you pass the functions.

Parameters
NameTypeDefaultDescription
valuestringThe value to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# round( number, [places] ) ⇒ number

Return a number rounded to the specified amount of places. This is the rounding function used internally by the formatter (symmetric arithmetic rounding).

Parameters
NameTypeDefaultDescription
numbernumberThe number to round.
[places]number0The number of decimals to round to.
Returns

number – A rounded number.


# tokenize( pattern ) ⇒ Array<FormatToken>

Breaks a format pattern string into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: 'zero',value: '0',raw: '0'},{type: 'point',value: '.',raw: '.'},{type: 'zero',value: '0',raw: '0'},{type: 'percent',value: '%',raw: '%'}]

Token types may be found as an Object as the tokenTypes export of the package.

Parameters
NameTypeDescription
patternstringThe format pattern
Returns

Array<FormatToken> – a list of tokens


Constant

# tokenTypes = Readonly<Record<string, string>>

A dictionary of the types used to identify token variants.

See also:tokenize.

Properties
NameTypeDescription
AMPMstringAM/PM operator (AM/PM, A/P)
BREAKstringSemicolon operator indicating a break between format sections (;)
CALENDARstringCalendar modifier (B2)
CHARstringSingle non-operator character (m)
COLORstringColor modifier ([Black], [color 5])
COMMAstringPlain non-operator comma (,)
CONDITIONstringCondition modifier for a section ([>=10])
DATETIMEstringDate-time operator (mmmm, YY)
DBNUMstringNumber display modifier ([DBNum23])
DIGITstringA digit between 1 and 9 (3)
DURATIONstringTime duration ([ss])
ERRORstringUnidentifiable or illegal character (Ň)
ESCAPEDstringEscaped character (\E)
EXPstringExponent operator (E+)
FILLstringFill with char operator and operand (*_)
GENERALstringGeneral format operator (General)
GROUPstringNumber grouping operator (,)
HASHstringHash operator (digit if available) (#)
LOCALEstringLocale modifier ([$-1E020404])
MINUSstringMinus sign (-)
MODIFIERstringAn unidentified modifier ([Schwarz])
NATNUMstringNumber display modifier ([NatNum3])
PARENstringParenthesis character ())
PERCENTstringPercent operator (%)
PLUSstringPlus sign (+)
POINTstringDecimal point operator (.)
QMARKstringQuestion mark operator (digit or space if not available) (?)
SCALEstringScaling operator (,)
SKIPstringSkip with char operator and operand (*_)
SLASHstringSlash operator (/)
SPACEstringSpace ()
STRINGstringQuoted string ("days")
TEXTstringText output operator (@)
ZEROstringZero operator (digit or zero if not available) (0)

Types

# FormatDateInfo

An object detailing which date specifiers are used in a format pattern.

Properties
NameTypeDescription
clockType12 | 2412 if the pattern uses AM/PM clock else 24.
daybooleantrue if the pattern uses day of the month else false.
hoursbooleantrue if the pattern uses hours else false.
minutesbooleantrue if the pattern uses minutes else false.
monthbooleantrue if the pattern uses months else false.
secondsbooleantrue if the pattern uses seconds else false.
yearbooleantrue if the pattern uses years else false.

# FormatInfo

An object of information properties based on a format pattern.

Properties
NameTypeDescription
codestringCorresponds to Excel's CELL("format") functionality. It should match Excel's esoteric behaviour fairly well. See Microsoft's documentation.
color0 | 11 if the format uses color on the negative portion of the string, else a 0. This replicates Excel's CELL("color") functionality.
grouped0 | 11 if the positive portion of the format uses a thousands separator, else a 0.
isDatebooleanCorresponds to the output from isDateFormat.
isPercentbooleanCorresponds to the output from isPercentFormat.
isTextbooleanCorresponds to the output from isTextFormat.
levelnumberAn arbirarty number that represents the format's specificity if you want to compare one to another. Integer comparisons roughly match Excel's resolutions when it determines which format wins out.
maxDecimalsnumberThe maximum number of decimals this format will emit.
parentheses0 | 11 if the positive portion of the number format contains an open parenthesis, else a 0. This is replicates Excel's CELL("parentheses") functionality.
scalenumberThe multiplier used when formatting the number (100 for percentages).
type"currency" | "date" | "datetime" | "error" | "fraction" | "general" | "grouped" | "number" | "percent" | "scientific" | "text" | "time"A string identifier for the type of the number formatter.

# FormatToken

Properties
NameTypeDescription
rawstringRaw token source.
typestringToken type.
valueanyThe value of the token, cleaned of extra characters.

# LocaleData

An object of properties used by a formatter when printing a number in a certain locale.

Properties
NameTypeDescription
ampmArray<string>How AM and PM should be presented
boolArray<string>How TRUE and FALSE should be presented
dddArray<string>Shortened day names (Wed)
ddddArray<string>Long day names (Wednesday)
decimalstringSymbol used to separate integers from fractions (usually .)
exponentstringSymbol used to indicate an exponent (usually E)
groupstringSymbol used as a grouping separator (1,000,000 uses ,)
infinitystringSymbol used to indicate infinite values ()
mmmArray<string>Short month names for the Gregorian calendar (Nov)
mmm6Array<string>Short month names for the Islamic calendar (Raj.)
mmmmArray<string>Long month names for the Gregorian calendar (November)
mmmm6Array<string>Long month names for the Islamic calendar (Rajab)
nanstringSymbol used to indicate NaN values (NaN)
negativestringSymbol used to indicate positive numbers (usually -)
percentstringSymbol used to indicate a percentage (usually %)
positivestringSymbol used to indicate positive numbers (usually +)
preferMDYbooleanIs the prefered date format month first (12/31/2025) or day first (31/12/2025)

# LocaleToken

An object of properties for a locale tag.

Properties
NameTypeDescription
langstringThe basic tag such as zh_CN or fi
languagestringThe language section (zh for zh_CN)
territorystringThe territory section (CN for zh_CN)

# ParseData

Properties
NameTypeDescription
vnumber | booleanthe value
[z]stringnumber format pattern

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); numfmt/API.md at master · borgar/numfmt · GitHub
Skip to content

Latest commit

History

History
667 lines (452 loc) · 48.4 KB

File metadata and controls

667 lines (452 loc) · 48.4 KB

Numfmt API

Functions

Constant

Types

Functions

# addLocale( localeSettings, l4e ) ⇒ LocaleData

Register locale data for a language so for use when formatting.

Any partial set of properties may be returned to have the defaults used where properties are missing.

See also: {LocaleData}.

Parameters
NameTypeDefaultDescription
localeSettingsobjectA collection of settings for a locale.
localeSettings.[ampm]Array<string>["AM","PM"]How AM and PM should be presented.
localeSettings.[bool]Array<string>["TRUE", "FALSE"]How TRUE and FALSE should be presented.
localeSettings.[ddd]Array<string>["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]Shortened day names (e.g. Wed)
localeSettings.[dddd]Array<string>["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]Long day names (e.g. Wednesday)
localeSettings.[decimal]string"."Symbol used to separate integers from fractions (usually .)
localeSettings.[exponent]string"E"Symbol used to indicate an exponent (usually E)
localeSettings.[group]string"\u00a0"Symbol used as a grouping separator (1,000,000 uses ,)
localeSettings.[infinity]string"∞"Symbol used to indicate infinite values ()
localeSettings.[mmm]Array<string>["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]Short month names for the Gregorian calendar (e.g. Nov)
localeSettings.[mmm6]Array<string>["Muh.", "Saf.", "Rab. I", "Rab. II", "Jum. I", "Jum. II", "Raj.", "Sha.", "Ram.", "Shaw.", "Dhuʻl-Q.", "Dhuʻl-H."]Short month names for the Islamic calendar (e.g. Raj.)
localeSettings.[mmmm]Array<string>["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]Long month names for the Gregorian calendar (e.g. November)
localeSettings.[mmmm6]Array<string>["Muharram", "Safar", "Rabiʻ I", "Rabiʻ II", "Jumada I", "Jumada II", "Rajab", "Shaʻban", "Ramadan", "Shawwal", "Dhuʻl-Qiʻdah", "Dhuʻl-Hijjah"]Long month names for the Islamic calendar (e.g. Rajab)
localeSettings.[nan]string"NaN"Symbol used to indicate NaN values (NaN)
localeSettings.[negative]string"-"Symbol used to indicate positive numbers (usually -)
localeSettings.[percent]string"%"Symbol used to indicate a percentage (usually %)
localeSettings.[positive]string"+"Symbol used to indicate positive numbers (usually +)
localeSettings.[preferMDY]booleanfalseIs the prefered date format month first (12/31/2025) or day first (31/12/2025)
l4estringA string BCP 47 tag of the locale.
Returns

LocaleData – - A full collection of settings for a locale


# dateFromSerial( serialDate, [options = {}] ) ⇒ Array<number>

Convert a spreadsheet serial date to an array of date parts. Accurate to a second.

// output as [ Y, M, D, h, m, s ]dateFromSerial(28627);// [ 1978, 5, 17, 0, 0, 0 ]
Parameters
NameTypeDefaultDescription
serialDatenumberThe date
[options]object{}The options
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug.
Returns

Array<number> – returns an array of date parts


# dateToSerial( date, [options = {}] ) ⇒ number | null

Convert a native JavaScript Date, or array to an spreadsheet serial date.

Returns a serial date number if input was a Date object or an array of numbers, a null.

// input as DatedateToSerial(newDate(1978,5,17));// 28627// input as [ Y, M, D, h, m, s ]dateToSerial([1978,5,17]);// 28627// other inputdateToSerial("something else");// null
Parameters
NameTypeDefaultDescription
dateDate | Array<number>The date
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally time zone will be taken into account. This makes the conversion to serial date ignore the timezone offset.
Returns

number | null – The date as a spreadsheet serial date, or null.


# format( pattern, value, [options = {}] ) ⇒ string

Formats a value as a string and returns the result.

  • Dates are normalized to spreadsheet style serial dates and then formatted. - Booleans are emitted as uppercase "TRUE" or "FALSE". - Null and Undefined will return an empty string "". - Any non number values will be stringified and passed through the text section of the format pattern. - NaNs and infinites will use the corresponding strings from the active locale.
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].bigintErrorNumberbooleanfalseShould the formatter switch to a plain string number format when trying to format a bigint that is out of bounds?
[options].dateErrorNumberbooleantrueShould the formatter switch to a General number format when trying to format a date that is out of bounds?
[options].dateErrorThrowsbooleanfalseShould the formatter throw an error when trying to format a date that is out of bounds?
[options].dateSpanLargebooleantrueExtends the allowed range of dates from Excel bounds (1900–9999) to Google Sheet bounds (0–99999).
[options].fillCharboolean""When the formatter encounters * it normally emits nothing instead of the * and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].invalidstring"######"The string emitted when no-throw mode fails to parse a pattern.
[options].leap1900booleantrueSimulate the Lotus 1-2-3 1900 leap year bug. It is a requirement in the Ecma OOXML specification so it is on by default.
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
[options].nbspbooleanfalseBy default the output will use a regular space, but in many cases you may desire a non-breaking-space instead.
[options].overflowstring"######"The string emitted when a formatter fails to format a date that is out of bounds.
[options].skipCharboolean""When the formatter encounters _ it normally emits a single space instead of the _ and the next character (like Excel TEXT function does). Setting this to a character will make the formatter emit that followed by the next one.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string – A formatted value


# formatColor( pattern, value, [options = {}] ) ⇒ string | number | null

Find the color appropriate to a value as dictated by a format pattern.

If the pattern defines colors, this function will emit the color appropriate to the value. If no colors were specified this function returns undefined.

constcolor=formatColor("[green]#,##0;[red]-#,##0",-10);console.log(color);// "red"constcolor=formatColor("[green]#,##0;-#,##0",-10);console.log(color);// null
Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
valueanyThe value to format.
[options]object{}Options
[options].ignoreTimezonebooleanfalseNormally when date objects are used with the formatter, time zone is taken into account. This makes the formatter ignore the timezone offset.
[options].indexColorsbooleantrueWhen indexed color modifiers are used ([Color 1]) the formatter will convert the index into the corresponding hex color of the default palette. When this option is set to false, the number will instead by emitted allowing you to index against a custom palette.
[options].throwsbooleantrueShould the formatter throw an error if a provided pattern is invalid. If false, a formatter will be constructed which instead outputs an error string (see invalid in this table).
Returns

string | number | null – A string color value as described by the pattern or a number if the indexColors option has been set to false.


# getFormatDateInfo( pattern ) ⇒ FormatDateInfo

Gets information about date codes use in a format string.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

FormatDateInfo – An object of format date properties.


# getFormatInfo( pattern, [options = {}] ) ⇒ FormatInfo

Returns an object detailing the properties and internals of a format parsed format pattern.

Parameters
NameTypeDefaultDescription
patternstringA format pattern in the ECMA-376 number format.
[options]object{}Options
[options].currencystringLimit the patterns identified as currency to those that use the give string. If nothing is provided, patterns will be tagged as currency if one of the following currency symbols is used: ¤$£¥֏؋৳฿៛₡₦₩₪₫€₭₮₱₲₴₸₹₺₼₽₾₿
Returns

FormatInfo – An object of format properties.


# getLocale( locale ) ⇒ LocaleData | null

Used by the formatter to pull a locate from its registered locales. If subtag isn't available but the base language is, the base language is used. So if en-CA is not found, the formatter tries to find en else it returns a null.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale, or an Excel locale code.
Returns

LocaleData | null – - An object of format date properties.


# isDateFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a date pattern.

The pattern is considered a date pattern if any of its sections contain a date symbol (such as Y or H). Each section is restricted to be either a number or date format.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isPercentFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a percentage pattern.

The pattern is considered a percentage pattern if any of its sections contains an unescaped percentage symbol.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isTextFormat( pattern ) ⇒ boolean

Determine if a given format pattern is a text only pattern.

The pattern is considered text only if its definition is composed of a single section that includes that text symbol (@).

For example @ or @" USD" are text patterns but #;@ is not.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is date pattern, False otherwise.


# isValidFormat( pattern ) ⇒ boolean

Determine if a given format pattern is valid.

Parameters
NameTypeDescription
patternstringA format pattern in the ECMA-376 number format.
Returns

boolean – True if the specified pattern is valid, False otherwise.


# parseBool( value, [options = {}] ) ⇒ ParseData | null

Parse a string input and return its boolean value. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with one property:

  • v: the parsed value.

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe supposed boolean to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseDate( value, [options = {}] ) ⇒ ParseData | null

Parse a date or datetime string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseLocale( locale ) ⇒ LocaleToken

Parse a regular IETF BCP 47 locale tag and emit an object of its parts. Irregular tags and subtags are not supported.

Parameters
NameTypeDescription
localestringA BCP 47 string tag of the locale.
Returns

LocaleToken – - An object describing the locale.


# parseNumber( value, [options = {}] ) ⇒ ParseData | null

Parse a numeric string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. * z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe number to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseTime( value, [options = {}] ) ⇒ ParseData | null

Parse a time string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: the parsed value. - z: the number format of the input (if applicable).

See also:parseValue.

Parameters
NameTypeDefaultDescription
valuestringThe date to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# parseValue( value, [options = {}] ) ⇒ ParseData | null

Attempt to parse a "spreadsheet input" string input and return its value and format. If the input was not recognized or valid, the function returns a null, for valid input it returns an object with two properties:

  • v: The parsed value. For dates, this will be an Excel style serial date. - z: (Optionally) the number format string of the input. This property will not be present if it amounts to the General format.

parseValue() recognizes a wide range of dates and date-times, times, numbers, and booleans. Some examples:

// basic numberparseValue("-123");// { v: -123 }// formatted numberparseValue("$1,234");// { v: 1234, z: "$#,##0" }// a percentparseValue("12.3%");// { v: 0.123, z: "0.00%" }// a dateparseValue("07 October 1984");// { v: 30962, z: 'dd mmmm yyyy' }// an ISO formatted date-timeparseValue("1984-09-10 11:12:13.1234");// { v: 30935.46681855787, z: "yyyy-mm-dd hh:mm:ss" }// a booleanparseValue("false");// { v: false }

The formatting string outputted may not correspond exactly to the input. Rather, is it composed of certain elements which the input controls. This is comparable to how Microsoft Excel and Google Sheets parse pasted input. Some things you may expect:

  • Whitespace is ignored. - Decimal fractions are always represented by .00 regardless of how many digits were shown in the input. - Negatives denoted by parentheses [(1,234)] will not include the parentheses in the format string (the value will still by negative.) - All "scientific notation" returns the same format: 0.00E+00.

Internally the parser calls, parseNumber, parseDate, parseTime and parseBool. They work in the same way except with a more limited scope. You may want those function if you are limiting input to a smaller scope.

Be warned that the parser do not (yet) take locale into account so all input is assumed to be in "en-US". This means that 1,234.5 will parse, but 1.234,5 will not. Similarly, the order of date parts will be US centric. This may change in the future so be careful what options you pass the functions.

Parameters
NameTypeDefaultDescription
valuestringThe value to parse
[options]object{}Options
[options].localestring""A BCP 47 string tag. Locale default is english with a \u00a0 grouping symbol (see addLocale)
Returns

ParseData | null – An object of the parsed value and a corresponding format string


# round( number, [places] ) ⇒ number

Return a number rounded to the specified amount of places. This is the rounding function used internally by the formatter (symmetric arithmetic rounding).

Parameters
NameTypeDefaultDescription
numbernumberThe number to round.
[places]number0The number of decimals to round to.
Returns

number – A rounded number.


# tokenize( pattern ) ⇒ Array<FormatToken>

Breaks a format pattern string into a list of tokens.

The returned output will be an array of objects representing the tokens:

[{type: 'zero',value: '0',raw: '0'},{type: 'point',value: '.',raw: '.'},{type: 'zero',value: '0',raw: '0'},{type: 'percent',value: '%',raw: '%'}]

Token types may be found as an Object as the tokenTypes export of the package.

Parameters
NameTypeDescription
patternstringThe format pattern
Returns

Array<FormatToken> – a list of tokens


Constant

# tokenTypes = Readonly<Record<string, string>>

A dictionary of the types used to identify token variants.

See also:tokenize.

Properties
NameTypeDescription
AMPMstringAM/PM operator (AM/PM, A/P)
BREAKstringSemicolon operator indicating a break between format sections (;)
CALENDARstringCalendar modifier (B2)
CHARstringSingle non-operator character (m)
COLORstringColor modifier ([Black], [color 5])
COMMAstringPlain non-operator comma (,)
CONDITIONstringCondition modifier for a section ([>=10])
DATETIMEstringDate-time operator (mmmm, YY)
DBNUMstringNumber display modifier ([DBNum23])
DIGITstringA digit between 1 and 9 (3)
DURATIONstringTime duration ([ss])
ERRORstringUnidentifiable or illegal character (Ň)
ESCAPEDstringEscaped character (\E)
EXPstringExponent operator (E+)
FILLstringFill with char operator and operand (*_)
GENERALstringGeneral format operator (General)
GROUPstringNumber grouping operator (,)
HASHstringHash operator (digit if available) (#)
LOCALEstringLocale modifier ([$-1E020404])
MINUSstringMinus sign (-)
MODIFIERstringAn unidentified modifier ([Schwarz])
NATNUMstringNumber display modifier ([NatNum3])
PARENstringParenthesis character ())
PERCENTstringPercent operator (%)
PLUSstringPlus sign (+)
POINTstringDecimal point operator (.)
QMARKstringQuestion mark operator (digit or space if not available) (?)
SCALEstringScaling operator (,)
SKIPstringSkip with char operator and operand (*_)
SLASHstringSlash operator (/)
SPACEstringSpace ()
STRINGstringQuoted string ("days")
TEXTstringText output operator (@)
ZEROstringZero operator (digit or zero if not available) (0)

Types

# FormatDateInfo

An object detailing which date specifiers are used in a format pattern.

Properties
NameTypeDescription
clockType12 | 2412 if the pattern uses AM/PM clock else 24.
daybooleantrue if the pattern uses day of the month else false.
hoursbooleantrue if the pattern uses hours else false.
minutesbooleantrue if the pattern uses minutes else false.
monthbooleantrue if the pattern uses months else false.
secondsbooleantrue if the pattern uses seconds else false.
yearbooleantrue if the pattern uses years else false.

# FormatInfo

An object of information properties based on a format pattern.

Properties
NameTypeDescription
codestringCorresponds to Excel's CELL("format") functionality. It should match Excel's esoteric behaviour fairly well. See Microsoft's documentation.
color0 | 11 if the format uses color on the negative portion of the string, else a 0. This replicates Excel's CELL("color") functionality.
grouped0 | 11 if the positive portion of the format uses a thousands separator, else a 0.
isDatebooleanCorresponds to the output from isDateFormat.
isPercentbooleanCorresponds to the output from isPercentFormat.
isTextbooleanCorresponds to the output from isTextFormat.
levelnumberAn arbirarty number that represents the format's specificity if you want to compare one to another. Integer comparisons roughly match Excel's resolutions when it determines which format wins out.
maxDecimalsnumberThe maximum number of decimals this format will emit.
parentheses0 | 11 if the positive portion of the number format contains an open parenthesis, else a 0. This is replicates Excel's CELL("parentheses") functionality.
scalenumberThe multiplier used when formatting the number (100 for percentages).
type"currency" | "date" | "datetime" | "error" | "fraction" | "general" | "grouped" | "number" | "percent" | "scientific" | "text" | "time"A string identifier for the type of the number formatter.

# FormatToken

Properties
NameTypeDescription
rawstringRaw token source.
typestringToken type.
valueanyThe value of the token, cleaned of extra characters.

# LocaleData

An object of properties used by a formatter when printing a number in a certain locale.

Properties
NameTypeDescription
ampmArray<string>How AM and PM should be presented
boolArray<string>How TRUE and FALSE should be presented
dddArray<string>Shortened day names (Wed)
ddddArray<string>Long day names (Wednesday)
decimalstringSymbol used to separate integers from fractions (usually .)
exponentstringSymbol used to indicate an exponent (usually E)
groupstringSymbol used as a grouping separator (1,000,000 uses ,)
infinitystringSymbol used to indicate infinite values ()
mmmArray<string>Short month names for the Gregorian calendar (Nov)
mmm6Array<string>Short month names for the Islamic calendar (Raj.)
mmmmArray<string>Long month names for the Gregorian calendar (November)
mmmm6Array<string>Long month names for the Islamic calendar (Rajab)
nanstringSymbol used to indicate NaN values (NaN)
negativestringSymbol used to indicate positive numbers (usually -)
percentstringSymbol used to indicate a percentage (usually %)
positivestringSymbol used to indicate positive numbers (usually +)
preferMDYbooleanIs the prefered date format month first (12/31/2025) or day first (31/12/2025)

# LocaleToken

An object of properties for a locale tag.

Properties
NameTypeDescription
langstringThe basic tag such as zh_CN or fi
languagestringThe language section (zh for zh_CN)
territorystringThe territory section (CN for zh_CN)

# ParseData

Properties
NameTypeDescription
vnumber | booleanthe value
[z]stringnumber format pattern