File size: 16,122 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 |
import { defaultCurrencyOverrides } from './currencies';
import { getCachedFormatter } from './get-cached-formatter';
import type {
CurrencyObject,
CurrencyObjectOptions,
CurrencyFormatter,
CurrencyOverride,
} from './types';
export * from './types';
const fallbackLocale = 'en';
const fallbackCurrency = 'USD';
const geolocationEndpointUrl = 'https://public-api.wordpress.com/geo/';
// TODO clk numberFormatCurrency exported only for tests
export function createFormatter(): CurrencyFormatter {
let defaultLocale: string | undefined = undefined;
let geoLocation = '';
// If the user is inside the US using USD, they should only see `$` and not `US$`.
async function geolocateCurrencySymbol(): Promise< void > {
const geoData = await globalThis
.fetch?.( geolocationEndpointUrl )
.then( ( response ) => response.json() )
.catch( ( error ) => {
// Do nothing if the fetch fails.
// eslint-disable-next-line no-console
console.warn( 'Fetching geolocation for format-currency failed.', error );
} );
if ( ! containsGeolocationCountry( geoData ) ) {
return;
}
if ( ! geoData.country_short ) {
return;
}
geoLocation = geoData.country_short;
}
function getLocaleToUse( options: CurrencyObjectOptions ): string {
return options.locale ?? defaultLocale ?? getLocaleFromBrowser();
}
function getFormatter(
number: number,
code: string,
options: CurrencyObjectOptions
): Intl.NumberFormat {
const numberFormatOptions: Intl.NumberFormatOptions = {
style: 'currency',
currency: code,
...( options.stripZeros &&
Number.isInteger( number ) && {
/**
* There's an option called `trailingZeroDisplay` but it does not yet work
* in FF so we have to strip zeros manually.
*/
maximumFractionDigits: 0,
minimumFractionDigits: 0,
} ),
...( options.signForPositive && { signDisplay: 'exceptZero' } ),
};
/**
* `numberingSystem` is an option to `Intl.NumberFormat` and is available
* in all major browsers according to
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options
* but is not part of the TypeScript types in `es2020`:
*
* https://github.com/microsoft/TypeScript/blob/cfd472f7aa5a2010a3115263bf457b30c5b489f3/src/lib/es2020.intl.d.ts#L272
*
* However, it is part of the TypeScript types in `es5`:
*
* https://github.com/microsoft/TypeScript/blob/cfd472f7aa5a2010a3115263bf457b30c5b489f3/src/lib/es5.d.ts#L4310
*
* Apparently calypso uses `es2020` so we cannot use that option here right
* now. Instead, we will use the unicode extension to the locale, documented
* here:
*
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/numberingSystem#adding_a_numbering_system_via_the_locale_string
*/
return getCachedFormatter( {
locale: `${ getLocaleToUse( options ) }-u-nu-latn`,
options: numberFormatOptions,
} );
}
/**
* Formats money with a given currency code.
*
* The currency will define the properties to use for this formatting, but
* those properties can be overridden using the options. Be careful when doing
* this.
*
* For currencies that include decimals, this will always return the amount
* with decimals included, even if those decimals are zeros. To exclude the
* zeros, use the `stripZeros` option. For example, the function will normally
* format `10.00` in `USD` as `$10.00` but when this option is true, it will
* return `$10` instead.
*
* Since rounding errors are common in floating point math, sometimes a price
* is provided as an integer in the smallest unit of a currency (eg: cents in
* USD or yen in JPY). Set the `isSmallestUnit` to change the function to
* operate on integer numbers instead. If this option is not set or false, the
* function will format the amount `1025` in `USD` as `$1,025.00`, but when the
* option is true, it will return `$10.25` instead.
*
* If the number is NaN, it will be treated as 0.
*
* If the currency code is not known, this will assume a default currency
* similar to USD.
*
* If `isSmallestUnit` is set and the number is not an integer, it will be
* rounded to an integer.
* @param {number} number number to format; assumed to be a float unless isSmallestUnit is set.
* @param {string} code currency code e.g. 'USD'
* @param {CurrencyObjectOptions} options options object
* @returns {string} A formatted string.
*/
function formatCurrency(
number: number,
code: string,
options: CurrencyObjectOptions = {}
): string {
const locale = getLocaleToUse( options );
const validCurrency = getValidCurrency( code );
const currencyOverride = getCurrencyOverride( validCurrency );
const currencyPrecision = getPrecisionForLocaleAndCurrency( locale, validCurrency );
const numberAsFloat = prepareNumberForFormatting( number, currencyPrecision ?? 0, options );
const formatter = getFormatter( numberAsFloat, validCurrency, options );
const parts = formatter.formatToParts( numberAsFloat );
return parts.reduce( ( formatted, part ) => {
switch ( part.type ) {
case 'currency':
if ( currencyOverride?.symbol ) {
return formatted + currencyOverride.symbol;
}
return formatted + part.value;
default:
return formatted + part.value;
}
}, '' );
}
/**
* Returns a formatted price object which can be used to manually render a
* formatted currency (eg: if you wanted to render the currency symbol in a
* different font size).
*
* The currency will define the properties to use for this formatting, but
* those properties can be overridden using the options. Be careful when doing
* this.
*
* For currencies that include decimals, this will always return the amount
* with decimals included, even if those decimals are zeros. To exclude the
* zeros, use the `stripZeros` option. For example, the function will normally
* format `10.00` in `USD` as `$10.00` but when this option is true, it will
* return `$10` instead.
*
* Since rounding errors are common in floating point math, sometimes a price
* is provided as an integer in the smallest unit of a currency (eg: cents in
* USD or yen in JPY). Set the `isSmallestUnit` to change the function to
* operate on integer numbers instead. If this option is not set or false, the
* function will format the amount `1025` in `USD` as `$1,025.00`, but when the
* option is true, it will return `$10.25` instead.
*
* Note that the `integer` return value of this function is not a number, but a
* locale-formatted string which may include symbols like spaces, commas, or
* periods as group separators. Similarly, the `fraction` property is a string
* that contains the decimal separator.
*
* If the number is NaN, it will be treated as 0.
*
* If the currency code is not known, this will assume a default currency
* similar to USD.
*
* If `isSmallestUnit` is set and the number is not an integer, it will be
* rounded to an integer.
* @param {number} number number to format; assumed to be a float unless isSmallestUnit is set.
* @param {string} code currency code e.g. 'USD'
* @param {CurrencyObjectOptions} options options object
* @returns {CurrencyObject} A formatted string e.g. { symbol:'$', integer: '$99', fraction: '.99', sign: '-' }
*/
function getCurrencyObject(
number: number,
code: string,
options: CurrencyObjectOptions = {}
): CurrencyObject {
const locale = getLocaleToUse( options );
const validCurrency = getValidCurrency( code );
const currencyOverride = getCurrencyOverride( validCurrency );
const currencyPrecision = getPrecisionForLocaleAndCurrency( locale, validCurrency );
const numberAsFloat = prepareNumberForFormatting( number, currencyPrecision ?? 0, options );
const formatter = getFormatter( numberAsFloat, validCurrency, options );
const parts = formatter.formatToParts( numberAsFloat );
let sign = '' as CurrencyObject[ 'sign' ];
let symbol = '$';
let symbolPosition = 'before' as CurrencyObject[ 'symbolPosition' ];
let hasAmountBeenSet = false;
let hasDecimalBeenSet = false;
let integer = '';
let fraction = '';
parts.forEach( ( part ) => {
switch ( part.type ) {
case 'currency':
symbol = currencyOverride?.symbol ?? part.value;
if ( hasAmountBeenSet ) {
symbolPosition = 'after';
}
return;
case 'group':
integer += part.value;
hasAmountBeenSet = true;
return;
case 'decimal':
fraction += part.value;
hasAmountBeenSet = true;
hasDecimalBeenSet = true;
return;
case 'integer':
integer += part.value;
hasAmountBeenSet = true;
return;
case 'fraction':
fraction += part.value;
hasAmountBeenSet = true;
hasDecimalBeenSet = true;
return;
case 'minusSign':
sign = '-' as CurrencyObject[ 'sign' ];
return;
case 'plusSign':
sign = '+' as CurrencyObject[ 'sign' ];
return;
}
} );
const hasNonZeroFraction = ! Number.isInteger( numberAsFloat ) && hasDecimalBeenSet;
return {
sign,
symbol,
symbolPosition,
integer,
fraction,
hasNonZeroFraction,
};
}
function getValidCurrency( code: string ): string {
if ( ! doesCurrencyExist( code ) ) {
// eslint-disable-next-line no-console
console.warn(
`getCurrencyObject was called with a non-existent currency "${ code }"; falling back to ${ fallbackCurrency }`
);
return fallbackCurrency;
}
return code;
}
function getCurrencyOverride( code: string ): CurrencyOverride | undefined {
if ( code === 'USD' && geoLocation !== '' && geoLocation !== 'US' ) {
return { symbol: 'US$' };
}
return defaultCurrencyOverrides[ code ];
}
function doesCurrencyExist( code: string ): boolean {
return Boolean( getCurrencyOverride( code ) );
}
/**
* Set a default locale for use by `formatCurrency` and `getCurrencyObject`.
*
* Note that this is global and will override any browser locale that is set!
* Use it with care.
*/
function setDefaultLocale( locale: string | undefined ): void {
defaultLocale = locale;
}
function getPrecisionForLocaleAndCurrency(
locale: string,
currency: string
): number | undefined {
const formatter = getFormatter( 0, currency, { locale } );
return formatter.resolvedOptions().maximumFractionDigits ?? 3; // 3 is the default for Intl.NumberFormat if minimumFractionDigits is not set
}
return {
formatCurrency,
getCurrencyObject,
setDefaultLocale,
geolocateCurrencySymbol,
};
}
function getLocaleFromBrowser() {
if ( typeof window === 'undefined' ) {
return fallbackLocale;
}
if ( window.navigator?.languages?.length > 0 ) {
return window.navigator.languages[ 0 ];
}
return window.navigator?.language ?? fallbackLocale;
}
function prepareNumberForFormatting(
number: number,
// currencyPrecision here must be the precision of the currency, regardless
// of what precision is requested for display!
currencyPrecision: number,
options: CurrencyObjectOptions
): number {
if ( isNaN( number ) ) {
// eslint-disable-next-line no-console
console.warn( 'formatCurrency was called with NaN' );
number = 0;
}
if ( options.isSmallestUnit ) {
if ( ! Number.isInteger( number ) ) {
// eslint-disable-next-line no-console
console.warn(
'formatCurrency was called with isSmallestUnit and a float which will be rounded',
number
);
number = Math.round( number );
}
number = convertPriceForSmallestUnit( number, currencyPrecision );
}
const scale = Math.pow( 10, currencyPrecision );
return Math.round( number * scale ) / scale;
}
function convertPriceForSmallestUnit( price: number, precision: number ): number {
return price / getSmallestUnitDivisor( precision );
}
function getSmallestUnitDivisor( precision: number ): number {
return 10 ** precision;
}
interface WithGeoCountry {
country_short: string;
}
function containsGeolocationCountry( response: unknown ): response is WithGeoCountry {
return typeof ( response as WithGeoCountry )?.country_short === 'string';
}
const defaultFormatter = createFormatter();
export async function geolocateCurrencySymbol() {
return defaultFormatter.geolocateCurrencySymbol();
}
/**
* Formats money with a given currency code.
*
* The currency will define the properties to use for this formatting, but
* those properties can be overridden using the options. Be careful when doing
* this.
*
* For currencies that include decimals, this will always return the amount
* with decimals included, even if those decimals are zeros. To exclude the
* zeros, use the `stripZeros` option. For example, the function will normally
* format `10.00` in `USD` as `$10.00` but when this option is true, it will
* return `$10` instead.
*
* Since rounding errors are common in floating point math, sometimes a price
* is provided as an integer in the smallest unit of a currency (eg: cents in
* USD or yen in JPY). Set the `isSmallestUnit` to change the function to
* operate on integer numbers instead. If this option is not set or false, the
* function will format the amount `1025` in `USD` as `$1,025.00`, but when the
* option is true, it will return `$10.25` instead.
*
* If the number is NaN, it will be treated as 0.
*
* If the currency code is not known, this will assume a default currency
* similar to USD.
*
* If `isSmallestUnit` is set and the number is not an integer, it will be
* rounded to an integer.
*/
export function formatCurrency( ...args: Parameters< typeof defaultFormatter.formatCurrency > ) {
return defaultFormatter.formatCurrency( ...args );
}
/**
* Returns a formatted price object which can be used to manually render a
* formatted currency (eg: if you wanted to render the currency symbol in a
* different font size).
*
* The currency will define the properties to use for this formatting, but
* those properties can be overridden using the options. Be careful when doing
* this.
*
* For currencies that include decimals, this will always return the amount
* with decimals included, even if those decimals are zeros. To exclude the
* zeros, use the `stripZeros` option. For example, the function will normally
* format `10.00` in `USD` as `$10.00` but when this option is true, it will
* return `$10` instead.
*
* Since rounding errors are common in floating point math, sometimes a price
* is provided as an integer in the smallest unit of a currency (eg: cents in
* USD or yen in JPY). Set the `isSmallestUnit` to change the function to
* operate on integer numbers instead. If this option is not set or false, the
* function will format the amount `1025` in `USD` as `$1,025.00`, but when the
* option is true, it will return `$10.25` instead.
*
* Note that the `integer` return value of this function is not a number, but a
* locale-formatted string which may include symbols like spaces, commas, or
* periods as group separators. Similarly, the `fraction` property is a string
* that contains the decimal separator.
*
* If the number is NaN, it will be treated as 0.
*
* If the currency code is not known, this will assume a default currency
* similar to USD.
*
* If `isSmallestUnit` is set and the number is not an integer, it will be
* rounded to an integer.
*/
export function getCurrencyObject(
...args: Parameters< typeof defaultFormatter.getCurrencyObject >
) {
return defaultFormatter.getCurrencyObject( ...args );
}
/**
* Set a default locale for use by `formatCurrency` and `getCurrencyObject`.
*
* Note that this is global and will override any browser locale that is set!
* Use it with care.
*/
export function setDefaultLocale(
...args: Parameters< typeof defaultFormatter.setDefaultLocale >
) {
return defaultFormatter.setDefaultLocale( ...args );
}
export default defaultFormatter.formatCurrency;
|