Link Search Menu Expand Document

getNumberFormatterSource() function

Returns a string of JavaScript source that evaluates to a number formatter function with the same (value: number) => string signature as the function returned by getNumberFormatter().

Signature:

export declare function getNumberFormatterSource(locales: string | string[], skeleton: string | Skeleton, currency?: string | null, onError?: (err: NumberFormatError) => void): string;

Parameters

Parameter Type Description
locales string | string[] One or more valid BCP 47 language tags, e.g. fr or en-CA
skeleton string | Skeleton An ICU NumberFormatter pattern or ::-prefixed skeleton string, or a parsed Skeleton structure
currency string | null If skeleton is a pattern string that includes ยค tokens, their skeleton representation requires a three-letter currency code.
onError (err: NumberFormatError) => void If defined, will be called separately for each encountered parsing error and unsupported feature.

Returns:

string

Remarks

The returned function will memoize an Intl.NumberFormat instance that makes use of features provided by the Unified API Proposal.

Example

import { getNumberFormatterSource } from '@messageformat/number-skeleton'

getNumberFormatterSource('en', '::percent', console.error)
// '(function() {\n' +
// '  var opt = {"style":"percent"};\n' +
// '  var nf = new Intl.NumberFormat(["en"], opt);\n' +
// '  var mod = function(n) { return n * 0.01; };\n' +
// '  return function(value) { return nf.format(mod(value)); }\n' +
// '})()'

const src = getNumberFormatterSource('en-CA', ':: currency/CAD unit-width-narrow', console.error)
// '(function() {\n' +
// '  var opt = {"style":"currency","currency":"CAD","currencyDisplay":"narrowSymbol","unitDisplay":"narrow"};\n' +
// '  var nf = new Intl.NumberFormat(["en-CA"], opt);\n'
// '  return function(value) { return nf.format(value); }\n' +
// '})()'
const fmt = new Function(`return ${src}`)()
fmt(42) // '$42.00'