Prvi commit

This commit is contained in:
David Štaleker
2023-05-12 09:00:07 +02:00
parent d3ffe93e42
commit 03b92525d7
14757 changed files with 9251133 additions and 53 deletions

View File

@@ -0,0 +1,28 @@
## [new] Globalize( locale|cldr )
Create a Globalize instance.
### Parameters
#### locale|cldr
Locale string or [Cldr instance](https://github.com/rxaviers/cldrjs) of the instance.
### Example
Prior to creating any Globalize instance, you must load `cldr/supplemental/likelySubtags.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
```javascript
var en = new Globalize( "en" );
// You can optionally omit the `new` operator.
var pt = Globalize( "pt" );
en.formatNumber( 3.1415 );
// > 3.142
pt.formatNumber( 3.1415 );
// > 3,142
```

View File

@@ -0,0 +1,96 @@
## Globalize.load( cldrJSONData, ... )
This method allows you to load CLDR JSON locale data. `Globalize.load()` is a proxy to `Cldr.load()`.
This method can be called as many times as needed. All passed JSON objects are deeply merged internally.
For more information, see https://github.com/rxaviers/cldrjs#readme.
### Parameters
#### cldrJSONData
A JSON object with CLDR data. See [Getting Started](#../../../README.md#2-cldr-content) for more information.
### Example
```javascript
Globalize.load({
"main": {
"en": {
"identity": {
"version": {
"_cldrVersion": "25",
"_number": "$Revision: 91 $"
},
"generation": {
"_date": "$Date: 2014-03-13 22:27:12 -0500 (Thu, 13 Mar 2014) $"
},
"language": "en"
},
"dates": {
"calendars": {
"gregorian": {
"months": {
"format": {
"abbreviated": {
"1": "Jan",
"2": "Feb",
"3": "Mar",
"4": "Apr",
"5": "May",
"6": "Jun",
"7": "Jul",
"8": "Aug",
"9": "Sep",
"10": "Oct",
"11": "Nov",
"12": "Dec"
}
}
},
"dayPeriods": {
"format": {
"wide": {
"am": "AM",
"am-alt-variant": "am",
"noon": "noon",
"pm": "PM",
"pm-alt-variant": "pm"
}
}
},
"dateFormats": {
"medium": "MMM d, y"
},
"timeFormats": {
"medium": "h:mm:ss a",
},
"dateTimeFormats": {
"medium": "{1}, {0}"
}
}
}
},
"numbers": {
"defaultNumberingSystem": "latn",
"symbols-numberSystem-latn": {
"group": ","
},
"decimalFormats-numberSystem-latn": {
"standard": "#,##0.###"
}
}
}
},
"supplemental": {
"version": {
"_cldrVersion": "25",
"_number": "$Revision: 91 $"
},
"likelySubtags": {
"en": "en-Latn-US",
}
}
});
```

View File

@@ -0,0 +1,43 @@
## Globalize.locale( [locale|cldr] )
Set default locale, or get it if locale argument is omitted.
Return the default [Cldr instance](https://github.com/rxaviers/cldrjs).
An application that supports globalization and/or localization will need to have a way to determine the user's preference. Attempting to automatically determine the appropriate locale is useful, but it is good practice to always offer the user a choice, by whatever means.
Whatever your mechanism, it is likely that you will have to correlate the user's preferences with the list of locale data supported in the app. This method allows you to select the best match given the locale data that you have included and to set the Globalize locale to the one which the user prefers.
LanguageMatching TBD (CLDR's spec http://www.unicode.org/reports/tr35/#LanguageMatching).
### Parameters
#### locale|cldr
- The locale string, e.g., `"en"`, `"pt-BR"`, or `"zh-Hant-TW"`. Or,
- The [Cldr instance](https://github.com/rxaviers/cldrjs), e.g., new `Cldr( "en" )`.
### Example
Prior to using this function, you must load `cldr/supplemental/likelySubtags.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
```javascript
// Set "pt" as our default locale.
Globalize.locale( "pt" );
// Get default locale.
Globalize.locale();
// > {
// attributes: {
// "languageId": "pt",
// "maxLanguageId": "pt_Latn_BR",
// "language": "pt",
// "script": "Latn",
// "territory": "BR",
// "region": "BR"
// },
// some more stuff...
// }
```

View File

@@ -0,0 +1,196 @@
## .currencyFormatter( currency [, options] ) ➜ function( value )
Return a function that formats a `currency` according to the given `options` or locale's defaults.
The returned function is invoked with one argument: the Number `value` to be formatted.
### Parameters
#### currency
3-letter currency code as defined by ISO 4217, eg. `"USD"`.
#### options.style
Optional. String `"symbol"` (default), `"accounting"`, `"code"` or `"name"`. See [`.numberFormatter( [options] )`](../number/number-formatter.md) for more options.
#### value
Number to be formatted, eg. `9.99`.
### Example
#### Static Formatter
Prior to using any currency methods, you must load `cldr/main/{locale}/currencies.json`, `cldr/supplemental/currencyData.json`, and the CLDR content required by the number module. If using plural messages, you also must load the CLDR content required by the plural module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
#### Using the default options
You can use the static method `Globalize.currencyFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.currencyFormatter( "USD" );
formatter( 9.99 );
// > "$9.99"
```
#### Instance Formatter
You can use the instance method `.currencyFormatter()`, which uses the instance locale.
```javascript
var deFormatter = Globalize( "de" ).currencyFormatter( "EUR" ),
zhFormatter = Globalize( "zh" ).currencyFormatter( "EUR" );
deFormatter( 9.99 );
// > "9,99 €"
zhFormatter( 9.99 );
// > "€ 9.99"
```
For comparison, follow the formatting output of different symbols in different locales.
| 3-letter currency code | en (English) | de (German) | zh (Chinese) |
| ---------------------------------- | ------------ | ----------- | ------------ |
| `.currencyFormatter( "USD" )( 1 )` | `$1.00` | `1,00 $` | `US$ 1.00` |
| `.currencyFormatter( "EUR" )( 1 )` | `€1.00` | `1,00 €` | `€ 1.00` |
| `.currencyFormatter( "CNY" )( 1 )` | `CN¥1.00` | `1,00 CN¥` | `¥ 1.00` |
| `.currencyFormatter( "JPY" )( 1 )` | `¥1` | `1 ¥` | `JP¥ 1` |
| `.currencyFormatter( "GBP" )( 1 )` | `£1.00` | `1,00 £` |  1.00` |
| `.currencyFormatter( "BRL" )( 1 )` | `R$1.00` | `1,00 R$` | `R$ 1.00` |
#### Using alternative `options.symbolForm`
Using the narrow symbol form, the same symbols may be used for multiple currencies. Thus the symbol may be ambiguous, and should only be used where the context is clear.
```js
Globalize( "en" ).currencyFormatter( "HKD" )( 1 );
// > "HK$1.00"
Globalize( "en" ).currencyFormatter( "HKD", { symbolForm: "narrow" } )( 1 );
// > "$1.00"
```
#### Configuring style
For the accounting variation of the symbol format, use `style: "accounting"`.
```javascript
var formatter = Globalize( "en" ).currencyFormatter( "USD", {
style: "accounting"
});
formatter( -1 );
// > "($1.00)"
```
For plural messages, use `style: "name"`.
```javascript
var formatter = Globalize( "en" ).currencyFormatter( "USD", {
style: "name"
});
formatter( 0 );
// > "0.00 US dollars"
formatter( 1 );
// > "1.00 US dollar"
```
For comparison, follow the formatting output of different symbols in different locales using the plural messages `Globalize( locale ).currencyFormatter( currency, { style: "name" } )( 1 )`.
| 3-letter currency code | en (English) | de (German) | zh (Chinese) |
| ---------------------- | ----------------------------- | -------------------------------- | ------------ |
| `USD` | `1.00 US dollar` | `1,00 US-Dollar` | `1.00美元` |
| `EUR` | `1.00 euro` | `1,00 Euro` | `1.00欧元` |
| `CNY` | `1.00 Chinese yuan` | `1,00 Chinesischer Yuan` | `1.00人民币` |
| `JPY` | `1 Japanese yen` | `1 Japanischer Yen` | `1日元` |
| `GBP` | `1.00 British pound sterling` | `1,00 Britisches Pfund Sterling` | `1.00英镑` |
| `BRL` | `1.00 Brazilian real` | `1,00 Brasilianischer Real` | `1.00巴西雷亚尔` |
For the international currency code, use `style: "code"`.
```javascript
var formatter = Globalize( "en" ).currencyFormatter( "USD", {
style: "code"
});
formatter( 9.99 );
// > "9.99 USD"
```
#### Configuring inherited number options
Override the number of digits, grouping separators, rounding function or any other [`.numberFormatter()` options](../number/number-formatter.md).
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.currencyFormatter( "USD", {
minimumFractionDigits: 0,
style: "name"
});
formatter( 1 );
// > "1 US dollar"
formatter = Globalize.currencyFormatter( "USD", {
round: "ceil"
});
formatter( 1.491 );
// > "$1.50"
```
#### Formatting Compact Currencies
```js
var shortFormatter = Globalize( "en" ).currencyFormatter( "USD", {
compact: "short"
});
var longFormatter = Globalize( "en" ).currencyFormatter( "USD", {
compact: "long"
});
shortFormatter( 12830000000 );
// > "$13B"
longFormatter( 12830000000 );
// > "$13 billion"
```
The minimumSignificantDigits and maximumSignificantDigits options are specially useful to control the number of digits to display.
```js
Globalize( "en" ).formatCurrency( 12830000000, "USD", {
compact: "short",
minimumSignificantDigits: 3,
maximumSignificantDigits: 3
});
// > "$12.8B"
```
#### Performance Suggestion
For improved performance on iterations, first create the formatter. Then, reuse it on each loop.
```javascript
var formatter = Globalize( "en" ).currencyFormatter( "USD" );
renderInvoice({
prices: prices.map(function( price ) {
return formatter( price );
})
});
```

View File

@@ -0,0 +1,117 @@
## .currencyToPartsFormatter( currency [, options] ) ➜ function( value )
Return a function that formats a `currency` into parts tokens according to the given `options` or locale's defaults.
The returned function is invoked with one argument: the Number `value` to be formatted.
### Parameters
#### currency
3-letter currency code as defined by ISO 4217, eg. `"USD"`.
#### options
Please, see [.currencyFormatter() options](./currency-formatter.md#parameters).
#### value
Number to be formatted, eg. `9.99`.
### Returns
An Array of objects containing the formatted currency in parts. The returned structure looks like this:
```js
[
{ type: "day", value: "17" },
{ type: "weekday", value: "Monday" }
]
```
Possible types are the following:
- `currency`
The currency string, such as the symbols `"$"` and `"€"` or the name `"Dollar"`, `"Euro"` depending on which style is used.
Please, see [.numberToPartsFormatter()](../number/number-to-parts-formatter.md#returns) for details about the inherited number parts such as `decimal`, `fraction`, `group`, `infinity`, `integer`, `literal`, `minusSign`, `nan`, `plusSign`, `percentSign`, and `compact`.
### Example
Prior to using any currency methods, you must load `cldr/main/{locale}/currencies.json`, `cldr/supplemental/currencyData.json`, and the CLDR content required by the number module. If using plural messages, you also must load the CLDR content required by the plural module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
#### Static Formatter
#### Using the default options
You can use the static method `Globalize.currencyToPartsFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.currencyToPartsFormatter( "USD" );
formatter( 9.99 );
// > [
// { "type": "currency", "value": "$" },
// { "type": "integer", "value": "9" },
// { "type": "decimal", "value": "." },
// { "type": "fraction", "value": "99" }
// ]
```
#### Instance Formatter
You can use the instance method `.currencyFormatter()`, which uses the instance locale.
```javascript
var deFormatter = Globalize( "de" ).currencyToPartsFormatter( "EUR" ),
zhFormatter = Globalize( "zh" ).currencyToPartsFormatter( "EUR" );
deFormatter( 9.99 );
// > [
// { "type": "integer", "value": "9" },
// { "type": "decimal", "value": "," },
// { "type": "fraction", "value": "99" },
// { "type": "literal", "value": " " },
// { "type": "currency", "value": "€" }
// ]
zhFormatter( 9.99 );
// > [
// { "type": "currency", "value": "€" },
// { "type": "integer", "value": "9" },
// { "type": "decimal", "value": "." },
// { "type": "fraction", "value": "99" }
// ]
```
The information is available separately and it can be formatted and concatenated again in a customized way. For example by using [`Array.prototype.map()`][], [arrow functions][], a [switch statement][], [template literals][], and [`Array.prototype.reduce()`][].
[`Array.prototype.map()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
[arrow functions]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
[switch statement]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
[template literals]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
[`Array.prototype.reduce()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
#### More Examples
Please, see [.currencyFormatter() example](./currency-formatter.md#example) for additional examples such as using alternative `symbolForm`, configuring `style` (symbol, accounting, and name styles), and the inherited number options (e.g., compact numbers).
#### Performance Suggestion
For improved performance on iterations, first create the formatter. Then, reuse it on each loop.
```javascript
var formatter = Globalize( "en" ).currencyToPartsFormatter( "USD" );
renderInvoice({
prices: prices.map(function( price ) {
return formatter( price );
})
});
```

View File

@@ -0,0 +1,203 @@
## .dateFormatter( [options] ) ➜ function( value )
Return a function that formats a date according to the given `options`. The default formatting is numeric year, month, and day (i.e., `{ skeleton: "yMd" }`.
The returned function is invoked with one argument: the Date instance `value` to be formatted.
### Parameters
#### options.skeleton
String value indicating a skeleton (see description above), eg. `{ skeleton: "GyMMMd" }`.
Skeleton provides a more flexible formatting mechanism than the predefined list `full`, `long`, `medium`, or `short` represented by date, time, or datetime. Instead, they are an open-ended list of patterns containing only date field information, and in a canonical order. For a complete list of skeleton patterns [check the unicode CLDR documentation](http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table).
For example:
| locale | `"GyMMMd"` skeleton |
| ------ | ------------------------- |
| *en* | `"Apr 9, 2014 AD"` |
| *zh* | `"公元2014年4月9日"` |
| *es* | `"9 abr. de 2014 d. C."` |
| *ar* | `"٩ أبريل، ٢٠١٤ م"` |
| *pt* | `"9 de abr de 2014 d.C."` |
#### options.date
One of the following String values: `full`, `long`, `medium`, or `short`, eg., `{ date: "full" }`.
#### options.time
One of the following String values: `full`, `long`, `medium`, or `short`, eg., `{ time: "full" }`.
#### options.datetime
One of the following String values: `full`, `long`, `medium`, or `short`, eg., `{ datetime: "full" }`.
#### options.raw
String value indicating a machine [raw pattern (anything in the "Sym." column)](http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table) eg. `{ raw: "dd/mm" }`. Note this is NOT recommended for i18n in general. Use `skeleton` instead.
#### options.timeZone
String based on the time zone names of the [IANA time zone database](https://www.iana.org/time-zones), such as `"Asia/Shanghai"`, `"Asia/Kolkata"`, `"America/New_York"`.
#### value
Date instance to be formatted, eg. `new Date()`;
### Example
Prior to using any date methods, you must load `cldr/main/{locale}/ca-gregorian.json`, `cldr/main/{locale}/timeZoneNames.json`, `cldr/supplemental/metaZones.json`, `cldr/supplemental/timeData.json`, `cldr/supplemental/weekData.json`, and the CLDR content required by the number module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.dateFormatter();
formatter( new Date( 2010, 10, 30, 17, 55 ) );
// > "11/30/2010"
```
You can use the instance method `.dateFormatter()`, which uses the instance locale.
```javascript
var enFormatter = Globalize( "en" ).dateFormatter(),
deFormatter = Globalize( "de" ).dateFormatter();
enFormatter( new Date( 2010, 10, 30, 17, 55 ) );
// > "11/30/2010"
deFormatter( new Date( 2010, 10, 30, 17, 55 ) );
// > "30.11.2010"
```
#### Using short, medium, long, and full presets
Use convenient presets for `date`, `time`, or `datetime`. Their possible values are: `short`, `medium`, `long`, and `full`.
| `presetValue` | `Globalize( "en" ).dateFormatter( presetValue )( new Date( 2010, 10, 1, 17, 55 ) )` |
| ------------------------ | ---------------------------------------- |
| `{ date: "short" }` | `"11/1/10"` |
| `{ date: "medium" }` | `"Nov 1, 2010"` |
| `{ date: "long" }` | `"November 1, 2010"` |
| `{ date: "full" }` | `"Monday, November 1, 2010"` |
| `{ time: "short" }` | `"5:55 PM"` |
| `{ time: "medium" }` | `"5:55:00 PM"` |
| `{ time: "long" }` | `"5:55:00 PM PST"` |
| `{ time: "full" }` | `"5:55:00 PM Pacific Standard Time"` |
| `{ datetime: "short" }` | `"11/1/10, 5:55 PM"` |
| `{ datetime: "medium" }` | `"Nov 1, 2010, 5:55:00 PM"` |
| `{ datetime: "long" }` | `"November 1, 2010 at 5:55:00 PM PST"` |
| `{ datetime: "full" }` | `"Monday, November 1, 2010 at 5:55:00 PM Pacific Standard Time"` |
For comparison, follow the same formatter `{ datetime: "short" }` on different locales.
| locale | `Globalize( locale ).dateFormatter({ datetime: "short" })( new Date( 2010, 10, 1, 17, 55 ) )` |
| ---------------- | ---------------------------------------- |
| *en* | `"11/1/10, 5:55 PM"` |
| *en_GB* | `"01/11/2010 17:55"` |
| *zh* | `"10/11/1 下午5:55"` |
| *zh-u-nu-native* | `"一〇/一一/一 下午五:五五"` |
| *es* | `"1/11/10 17:55"` |
| *de* | `"01.11.10 17:55"` |
| *pt* | `"01/11/10 17:55"` |
| *ar* | `"١/١١/٢٠١٠ ٥،٥٥ م"` |
#### Using open-ended skeletons
Use open-ended skeletons for more flexibility (see its description [above](#parameters)). See some examples below.
| `skeleton` | `Globalize( "en" ).dateFormatter( skeleton )( new Date( 2010, 10, 1, 17, 55 ) )` |
| ---------------------------- | ---------------------------------------- |
| `{ skeleton: "E" }` | `"Tue"` |
| `{ skeleton: "EHm" }` | `"Tue 17:55"` |
| `{ skeleton: "EHms" }` | `"Tue 17:55:00"` |
| `{ skeleton: "Ed" }` | `"30 Tue"` |
| `{ skeleton: "Ehm" }` | `"Tue 5:55 PM"` |
| `{ skeleton: "Ehms" }` | `"Tue 5:55:00 PM"` |
| `{ skeleton: "Gy" }` | `"2010 AD"` |
| `{ skeleton: "GyMMM" }` | `"Nov 2010 AD"` |
| `{ skeleton: "GyMMMEd" }` | `"Tue, Nov 30, 2010 AD"` |
| `{ skeleton: "GyMMMd" }` | `"Nov 30, 2010 AD"` |
| `{ skeleton: "H" }` | `"17"` |
| `{ skeleton: "Hm" }` | `"17:55"` |
| `{ skeleton: "Hms" }` | `"17:55:00"` |
| `{ skeleton: "M" }` | `"11"` |
| `{ skeleton: "MEd" }` | `"Tue, 11/30"` |
| `{ skeleton: "MMM" }` | `"Nov"` |
| `{ skeleton: "MMMEd" }` | `"Tue, Nov 30"` |
| `{ skeleton: "MMMd" }` | `"Nov 30"` |
| `{ skeleton: "Md" }` | `"11/30"` |
| `{ skeleton: "d" }` | `"30"` |
| `{ skeleton: "h" }` | `"5 PM"` |
| `{ skeleton: "hm" }` | `"5:55 PM"` |
| `{ skeleton: "hms" }` | `"5:55:00 PM"` |
| `{ skeleton: "ms" }` | `"55:00"` |
| `{ skeleton: "y" }` | `"2010"` |
| `{ skeleton: "yM" }` | `"11/2010"` |
| `{ skeleton: "yMEd" }` | `"Tue, 11/30/2010"` |
| `{ skeleton: "yMMM" }` | `"Nov 2010"` |
| `{ skeleton: "yMMMEd" }` | `"Tue, Nov 30, 2010"` |
| `{ skeleton: "yMMMd" }` | `"Nov 30, 2010"` |
| `{ skeleton: "yMd" }` | `"11/30/2010"` |
| `{ skeleton: "yQQQ" }` | `"Q4 2010"` |
| `{ skeleton: "yQQQQ" }` | `"4th quarter 2010"` |
| `{ skeleton: "GyMMMEdhms" }` | `"Tue, Nov 30, 2010 AD, 5:55:00 PM"` |
| `{ skeleton: "Ehms" }` | `"Tue 5:55:00 PM"` |
| `{ skeleton: "yQQQHm" }` | `"Q4 2010, 17:55"` |
| `{ skeleton: "MMMEdhm" }` | `"Tue, Nov 30, 5:55 PM"` |
| `{ skeleton: "yMMMdhm" }` | `"Nov 30, 2010, 5:55 PM"` |
```javascript
var globalize = Globalize( "en" ),
date = new Date( 2010, 10, 30, 17, 55 ),
monthDayFormatter = globalize.dateFormatter({ skeleton: "MMMd" }),
hourMinuteSecondFormatter = globalize.dateFormatter({ skeleton: "Hms" });
monthDayFormatter( date );
// > "Nov 30"
hourMinuteSecondFormatter( date );
// > "17:55:00"
```
#### Using time zones
Using specific timeZones, i.e., using `options.timezone`. Note that prior to using it, you must load IANA time zone data.
```js
Globalize.loadTimeZone( require( "iana-tz-data" ) );
```
```js
Globalize.locale( "en" );
Globalize.dateFormatter({ datetime: "medium", timeZone: "America/Los_Angeles" })( new Date() );
// > "Nov 1, 2010, 12:55:00 PM"
Globalize.dateFormatter({ datetime: "medium", timeZone: "America/Sao_Paulo" })( new Date() )
// > "Nov 1, 2010, 5:55:00 PM"
Globalize.dateFormatter({ datetime: "full", timeZone: "Europe/Berlin" })( new Date() )
// > "Monday, November 1, 2010 at 8:55:00 PM Central European Standard Time"
```
#### Note on performance
For improved performance on iterations, first create the formatter. Then, reuse it on each loop.
```javascript
// In an application, this array could have a few hundred entries
var dates = [ new Date( 2010, 10, 30, 17, 55 ), new Date( 2015, 3, 18, 4, 25 ) ];
var formatter = Globalize( "en" ).dateFormatter({ time: "short" });
var formattedDates = dates.map(function( date ) {
return formatter( date );
});
// > Array [ "5:55 PM", "4:25 AM" ]
```

View File

@@ -0,0 +1,60 @@
## .dateParser( [options] ) ➜ function( value )
Return a function that parses a string representing a date into a JavaScript Date object according to the given `options`. The default parsing assumes numeric year, month, and day (i.e., `{ skeleton: "yMd" }`).
The returned function is invoked with one argument: the String `value` to be parsed.
### Parameters
#### options
See [.dateFormatter() options](./date-formatter.md#parameters).
#### value
String with date to be parsed, eg. `"11/1/10, 5:55 PM"`.
### Example
Prior to using any date methods, you must load `cldr/main/{locale}/ca-gregorian.json`, `cldr/main/{locale}/timeZoneNames.json`, `cldr/supplemental/timeData.json`, `cldr/supplemental/weekData.json`, and the CLDR content required by the number module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.dateParser()`, which uses the default locale.
```javascript
var parser;
Globalize.locale( "en" );
parser = Globalize.dateParser();
parser( "1/2/2013" );
// > Wed Jan 02 2013 00:00:00
Globalize.locale( "es" );
parser = Globalize.dateParser();
parser( "1/2/2013" );
// > Fri Feb 01 2013 00:00:00
```
You can use the instance method `.dateParser()`, which uses the instance locale.
```javascript
var esParser = Globalize( "es" ).dateParser({ date: short });
esParser( "1/2/13" );
// > Fri Feb 01 2013 00:00:00
```
For improved performance on iterations, first create the parser. Then, reuse it
on each loop.
```javascript
var formattedDates = [ new Date( a ), new Date( b ), ... ];
var parser = Globalize( "en" ).dateParser({ time: "short" });
dates = formattedDates.map(function( formattedDate ) {
return parser( formattedDate );
});
```

View File

@@ -0,0 +1,176 @@
## .dateToPartsFormatter( [options] ) ➜ function( value )
Return a function that formats a date into parts tokens according to the given `options`. The default formatting is numeric year, month, and day (i.e., `{ skeleton: "yMd" }`.
The returned function is invoked with one argument: the Date instance `value` to be formatted.
### Parameters
#### options
Please, see [.dateFormatter() options](./date-formatter.md#parameters).
#### value
Date instance to be formatted, eg. `new Date()`;
### Returns
An Array of objects containing the formatted date in parts. The returned structure looks like this:
```js
[
{ type: "day", value: "17" },
{ type: "weekday", value: "Monday" }
]
```
Possible types are the following:
- `day`
The string used for the day, e.g., `"17"`, `"١٦"`.
- `dayperiod`
The string used for the day period, e.g., `"AM"`, `"PM"`.
- `era`
The string used for the era, e.g., `"AD"`, `"d. C."`.
- `hour`
The string used for the hour, e.g., `"3"`, `"03"`.
- `literal`
The string used for separating date and time values, e.g., `"/"`, `", "`,
`"o'clock"`, `" de "`.
- `minute`
The string used for the minute, e.g., `"00"`.
- `month`
The string used for the month, e.g., `"12"`.
- `second`
The string used for the second, e.g., `"07"` or `"42"`.
- `zone`
The string used for the name of the time zone, e.g., `"EST".`
- `weekday`
The string used for the weekday, e.g., `"M"`, `"Monday"`, `"Montag".`
- `year`
The string used for the year, e.g., `"2012"`, `"96".`
### Example
Prior to using any date methods, you must load `cldr/main/{locale}/ca-gregorian.json`, `cldr/main/{locale}/timeZoneNames.json`, `cldr/supplemental/timeData.json`, `cldr/supplemental/weekData.json`, and the CLDR content required by the number module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.dateToPartsFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.dateToPartsFormatter();
formatter( new Date( 2010, 10, 30 ) );
// > [
// { "type": "month", "value": "11" },
// { "type": "literal", "value": "/" },
// { "type": "day", "value": "30" },
// { "type": "literal", "value": "/" },
// { "type": "year", "value": "2010" }
// ]
```
You can use the instance method `.dateToPartsFormatter()`, which uses the instance locale.
```javascript
var enFormatter = Globalize( "en" ).dateToPartsFormatter(),
deFormatter = Globalize( "de" ).dateToPartsFormatter();
enFormatter( new Date( 2010, 10, 30 ) );
// > [
// { "type": "month", "value": "11" },
// { "type": "literal", "value": "/" },
// { "type": "day", "value": "30" },
// { "type": "literal", "value": "/" },
// { "type": "year", "value": "2010" }
// ]
deFormatter( new Date( 2010, 10, 30 ) );
// > [
// { type: 'day', value: '30' },
// { type: 'literal', value: '.' },
// { type: 'month', value: '11' },
// { type: 'literal', value: '.' },
// { type: 'year', value: '2010' }
// ]
```
The information is available separately and it can be formatted and concatenated again in a customized way. For example by using [`Array.prototype.map()`][], [arrow functions][], a [switch statement][], [template literals][], and [`Array.prototype.reduce()`][].
[`Array.prototype.map()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
[arrow functions]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
[switch statement]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
[template literals]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
[`Array.prototype.reduce()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.dateToPartsFormatter({datetime: "short"});
formatter( new Date( 2010, 10, 30, 17, 55 ) ).map(({type, value}) => {
switch ( type ) {
case "year": return `<strong>${value}</strong>`;
default: return value;
}
}).join( "" );
// > "11/30/<strong>10</strong>, 5:55 PM"
```
Please, see [.dateFormatter() example](./date-formatter.md#example) for additional examples such as using `date`, `time`, `datetime`, and `skeleton` options.
For improved performance on iterations, first create the formatter. Then, reuse it on each loop.
```javascript
// In an application, this array could have a few hundred entries
var dates = [ new Date( 2010, 10, 30, 17, 55 ), new Date( 2015, 3, 18, 4, 25 ) ];
var formatter = Globalize( "en" ).dateToPartsFormatter({ time: "short" });
var formattedDates = dates.map(function( date ) {
return formatter( date );
});
// > [
// [
// { "type": "hour", "value": "5" },
// { "type": "literal", "value": ":" },
// { "type": "minute", "value": "55" },
// { "type": "literal", "value": " " },
// { "type": "dayperiod", "value": "PM" }
// ],
// [
// { "type": "hour", "value": "4" },
// { "type": "literal", "value": ":" },
// { "type": "minute", "value": "25" },
// { "type": "literal", "value": " " },
// { "type": "dayperiod", "value": "AM" }
// ]
// ]
```

View File

@@ -0,0 +1,29 @@
## Globalize.loadTimeZone( ianaTzData )
This method allows you to load IANA time zone data to enable `options.timeZone` feature on date formatters and parsers.
### Parameters
#### ianaTzData
A JSON object with zdumped IANA timezone data. Get the data via [`iana-tz-data`](https://github.com/rxaviers/iana-tz-data).
### Example
```javascript
Globalize.loadTimeZone({
"zoneData": {
...
"America": {
...
"New_York": {
abbrs: [],
untils: [],
offsets: [],
isdsts: []
}
...
}
}
});
```

View File

@@ -0,0 +1,105 @@
## .loadMessages( json )
Load messages data.
The first level of keys must be locales. For example:
```
{
en: {
hello: "Hello"
},
pt: {
hello: "Olá"
}
}
```
ICU MessageFormat pattern is supported: variable replacement, gender and plural inflections. For more information see [`.messageFormatter( path ) ➡ function([ variables ])`](./message-formatter.md).
The provided messages are stored along side other cldr data, under the "globalize-messages" key. This allows Globalize to reuse the traversal methods provided by cldrjs. You can inspect this data using `cldrjs.get("globalize-messages")`.
### Parameters
#### json
JSON object of messages data. Keys can use any character, except `/`, `{` and `}`. Values (i.e., the message content itself) can contain any character.
### Example
```javascript
Globalize.loadMessages({
pt: {
greetings: {
hello: "Olá",
bye: "Tchau"
}
}
});
Globalize( "pt" ).formatMessage( "greetings/hello" );
// > Olá
```
#### Multiline strings
Use Arrays as a convenience for multiline strings. The lines will be joined by a space.
```javascript
Globalize.loadMessages({
en: {
longText: [
"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi non",
"quis exercitationem culpa nesciunt nihil aut nostrum explicabo",
"reprehenderit optio amet ab temporibus asperiores quasi cupiditate.",
"Voluptatum ducimus voluptates voluptas?"
]
}
});
Globalize( "en" ).formatMessage( "longText" );
// > "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi non quis exercitationem culpa nesciunt nihil aut nostrum explicabo reprehenderit optio amet ab temporibus asperiores quasi cupiditate. Voluptatum ducimus voluptates voluptas?"
```
#### Messages inheritance
It's possible to inherit messages, for example:
```javascript
Globalize.loadMessages({
root: {
amen: "Amen"
},
de: {},
en: {},
"en-GB": {},
fr: {},
pt: {
amen: "Amém"
},
"pt-PT": {}
});
Globalize( "de" ).formatMessage( "amen" );
// > "Amen"
Globalize( "en" ).formatMessage( "amen" );
// > "Amen"
Globalize( "en-GB" ).formatMessage( "amen" );
// > "Amen"
Globalize( "fr" ).formatMessage( "amen" );
// > "Amen"
Globalize( "pt-PT" ).formatMessage( "amen" );
// > "Amém"
```
Note that `de`, `en`, `en-GB`, `fr`, and `pt-PT` are empty. `.formatMessage()` inherits `pt-PT` messages from `pt` (`pt-PT``pt`), and it inherits the other messages from root, eg. `en-GB``en-001``en``root`. Yes, `root` is the last bundle of the parent lookup.
Attention: On browsers, message inheritance only works if the optional dependency `cldr/unresolved` is loaded.
```html
<script src="cldr/unresolved.js"></script>
```

View File

@@ -0,0 +1,208 @@
## .messageFormatter( path ) ➡ function([ variables ])
Return a function that formats a message (using ICU message format pattern) given its path and a set of variables into a user-readable string. It supports pluralization and gender inflections.
Use [`Globalize.loadMessages( json )`](./load-messages.md) to load
messages data.
### Parameters
#### path
String or Array containing the path of the message content, eg., `"greetings/bye"`, or `[ "greetings", "bye" ]`.
#### variables
Optional. Variables can be Objects, where each property can be referenced by name inside a message; or Arrays, where each entry of the Array can be used inside a message, using numeric indices. When passing one or more arguments of other types, they're converted to an Array and used as such.
### Example
You can use the static method `Globalize.messageFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.loadMessages({
pt: {
greetings: {
bye: "Tchau"
}
}
});
Globalize.locale( "pt" );
formatter = Globalize.messageFormatter( "greetings/bye" );
formatter();
// > "Tchau"
```
You can use the instance method `.messageFormatter()`, which uses the instance locale.
```javascript
var pt = new Globalize( "pt" ),
formatter = pt.messageFormatter( "greetings/bye" );
formatter();
// > "Tchau"
```
#### Simple Variable Replacement
```javascript
var formatter;
Globalize.loadMessages({
en: {
hello: "Hello, {0} {1} {2}",
hey: "Hey, {first} {middle} {last}"
}
});
formatter = Globalize( "en" ).messageFormatter( "hello" );
// Numbered variables using Array.
formatter([ "Wolfgang", "Amadeus", "Mozart" ]);
// > "Hello, Wolfgang Amadeus Mozart"
// Numbered variables using function arguments.
formatter( "Wolfgang", "Amadeus", "Mozart" );
// > "Hello, Wolfgang Amadeus Mozart"
// Named variables using Object key-value pairs.
formatter = Globalize( "en" ).messageFormatter( "hey" );
formatter({
first: "Wolfgang",
middle: "Amadeus",
last: "Mozart"
});
// > "Hey, Wolfgang Amadeus Mozart"
```
#### Gender inflections
`select` can be used to format any message variations that works like a switch.
```javascript
var formatter;
// Note you can define multiple lines message using an Array of Strings.
Globalize.loadMessages({
en: {
party: [
"{hostGender, select,",
" female {{host} invites {guest} to her party}",
" male {{host} invites {guest} to his party}",
" other {{host} invites {guest} to their party}",
"}"
]
}
});
formatter = Globalize( "en" ).messageFormatter( "party" );
formatter({
guest: "Mozart",
host: "Beethoven",
hostGender: "male"
});
// > "Beethoven invites Mozart to his party"
```
#### Plural inflections
It uses the plural forms `zero`, `one`, `two`, `few`, `many`, or `other` (required). Note English only uses `one` and `other`. So, including `zero` will never get called, even when the number is 0. For more information see [`.pluralGenerator()`](../plural/plural-generator.md).
```javascript
var numberFormatter, taskFormatter,
en = new Globalize( "en" );
// Note you can define multiple lines message using an Array of Strings.
Globalize.loadMessages({
en: {
task: [
"You have {count, plural,",
" one {one task}",
" other {{formattedCount} tasks}",
"} remaining"
]
}
});
numberFormatter = en.numberFormatter();
taskFormatter = en.messageFormatter( "task" );
taskFormatter({
count: 1000,
formattedCount: numberFormatter( 1000 )
});
// > "You have 1,000 tasks remaining"
```
Literal numeric keys can be used in `plural` to match single, specific numbers.
```javascript
var taskFormatter,
en = new Globalize( "en" );
// Note you can define multiple lines message using an Array of Strings.
Globalize.loadMessages({
en: {
task: [
"You have {count, plural,",
" =0 {no tasks}",
" one {one task}",
" other {{formattedCount} tasks}",
"} remaining"
]
}
});
taskFormatter = Globalize( "en" ).messageFormatter( "task" );
taskFormatter({
count: 0,
formattedCount: en.numberFormatter( 0 )
});
// > "You have no tasks remaining"
```
You may find useful having the plural forms calculated with an offset applied.
Use `#` to output the resulting number. Note literal numeric keys do NOT use the
offset value.
```javascript
var likeFormatter,
en = new Globalize( "en" );
Globalize.loadMessages({
en: {
likeIncludingMe: [
"{0, plural, offset:1",
" =0 {Be the first to like this}",
" =1 {You liked this}",
" one {You and someone else liked this}",
" other {You and # others liked this}",
"}"
]
}
});
likeFormatter = Globalize( "en" ).messageFormatter( "likeIncludingMe" );
likeFormatter( 0 );
// > "Be the first to like this"
likeFormatter( 1 );
// > "You liked this"
likeFormatter( 2 );
// > "You and someone else liked this"
likeFormatter( 3 );
// > "You and 2 others liked this"
```
Read on [SlexAxton/messageFormatter.js][] for more information on regard of ICU MessageFormat.
[SlexAxton/messageFormatter.js]: https://github.com/SlexAxton/messageformat.js/#no-frills

View File

@@ -0,0 +1,202 @@
## .numberFormatter( [options] ) ➜ function( value )
Return a function that formats a number according to the given options.
The returned function is invoked with one argument: the Number `value` to be formatted.
### Parameters
#### options.style
Optional. String `decimal` (default), or `percent`.
#### options.minimumIntegerDigits
Optional. Non-negative integer Number value indicating the minimum integer digits to be used. Numbers will be padded with leading zeroes if necessary.
#### options.minimumFractionDigits, options.maximumFractionDigits
Optional. Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. Numbers will be rounded or padded with trailing zeroes if necessary. Either one or both of these properties must be present. If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns.
#### options.minimumSignificantDigits, options.maximumSignificantDigits
Optional. Positive integer Number values indicating the minimum and maximum fraction digits to be shown. Either none or both of these properties are present. If they are, they override minimum and maximum integer and fraction digits. The formatter uses however many integer and fraction digits are required to display the specified number of significant digits.
#### options.round
Optional. String with rounding method `ceil`, `floor`, `round` (default), or `truncate`.
#### options.useGrouping
Optional. Boolean (default is true) value indicating whether a grouping separator should be used.
#### options.compact
Optional. String `short` or `long` indicating which compact number format should be used to represent the number.
### Examples
#### Static Formatter
Prior to using any number methods, you must load `cldr/main/{locale}/numbers.json` and `cldr/supplemental/numberingSystems.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.numberFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.numberFormatter();
formatter( 3.141592 );
// > "3.142"
```
#### Instance Formatter
You can use the instance method `.numberFormatter()`, which uses the instance
locale.
```javascript
var arFormatter = Globalize( "ar" ).numberFormatter(),
esFormatter = Globalize( "es" ).numberFormatter(),
zhFormatter = Globalize( "zh-u-nu-native" ).numberFormatter();
arFormatter( 3.141592 );
// > "٣٫١٤٢"
esFormatter( 3.141592 );
// > "3,142"
zhFormatter( 3.141592 );
// > "三.一四二"
```
#### Configuring decimal places
The number of decimal places can be decreased or increased using `minimumFractionDigits` and `maximumFractionDigits`.
```javascript
Globalize.numberFormatter({ maximumFractionDigits: 2 })( 3.141592 );
// > "3.14"
Globalize.numberFormatter({ minimumFractionDigits: 2 })( 1.5 );
// > "1.50"
```
#### Configuring significant digits
The number of significant (non-zero) digits can be decreased or increased using `minimumSignificantDigits` and `maximumSignificantDigits`.
```javascript
var formatter = Globalize.numberFormatter({
minimumSignificantDigits: 1,
maximumSignificantDigits: 3
});
formatter( 3.141592 );
// > "3.14"
formatter = Globalize.numberFormatter({
minimumSignificantDigits: 1,
maximumSignificantDigits: 3
});
formatter( 12345 );
// > "12,300"
formatter = Globalize.numberFormatter({
minimumSignificantDigits: 1,
maximumSignificantDigits: 3
});
formatter( 0.00012345 );
// > "0.000123"
```
#### Formatting Percentages
Numbers can be formatted as percentages.
```javascript
var enFormatter = Globalize( "en" ).numberFormatter({
style: "percent",
minimumFractionDigits: 1,
maximumFractionDigits: 1
});
var frFormatter = Globalize( "fr" ).numberFormatter({
style: "percent",
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
enFormatter( 0.0016 );
// > "0.2%"
enFormatter( 0.0014 );
// > "0.1%"
frFormatter( 0.0005 );
// > "0,05 %"
```
#### Formatting Compact Numbers
Long numbers can be represented in a compact format, with `short` using abbreviated units and `long` using the full unit name.
```javascript
var shortFormatter = Globalize( "en" ).numberFormatter({
compact: "short"
});
var longFormatter = Globalize( "en" ).numberFormatter({
compact: "long"
});
shortFormatter( 27588910 );
// > "28M"
longFormatter( 27588910 );
// > "28 million"
```
The minimumSignificantDigits and maximumSignificantDigits options are specially useful to control the number of digits to display.
```js
Globalize( "en" ).formatNumber( 27588910, {
compact: "short",
minimumSignificantDigits: 3,
maximumSignificantDigits: 3
});
// > "27.6M"
```
#### Configuring Rounding
Numbers with a decreased amount of decimal places can be rounded up, rounded down, rounded arithmetically, or truncated by setting the `round` option to `ceil`, `floor`, `round` (default), or `truncate`.
```javascript
var formatter = Globalize.numberFormatter({
maximumFractionDigits: 2,
round: "ceil"
});
formatter( 3.141592 );
// > "3.15"
```
#### Performance Suggestions
For improved performance on iterations, the formatter should be created before the loop. Then, it can be reused in each iteration.
```javascript
var numbers = [ 1, 1, 2, 3, ... ];
var formatter = Globalize( "en" ).numberFormatter();
formattedNumbers = numbers.map(function( number ) {
return formatter( number );
});
```

View File

@@ -0,0 +1,130 @@
## .numberParser( [options] ) ➜ function( value )
Return a function that parses a String representing a number according to the given options. If value is invalid, `NaN` is returned.
The returned function is invoked with one argument: the String representing a number `value` to be parsed.
### Parameters
#### options
See [.numberFormatter() options](./number-formatter.md#parameters).
#### value
String with number to be parsed, eg. `"3.14"`.
### Example
Prior to using any number methods, you must load `cldr/main/{locale}/numbers.json` and `cldr/supplemental/numberingSystems.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.numberParser()`, which uses the default locale.
```javascript
var parser;
Globalize.locale( "en" );
parser = Globalize.numberParser();
parser( "3.14" );
// > 3.14
```
You can use the instance method `.numberParser()`, which uses the instance locale.
```javascript
var enParser = Globalize( "en" ).numberParser(),
esParser = Globalize( "es" ).numberParser();
enParser( "3.14" );
// > 3.14
esParser( "3,14" );
// > 3.14
```
Some more examples.
```javascript
var enParser = Globalize( "en" ).numberParser();
enParser( "12,735" );
// > 12735
enParser( "12,735.00" );
// > 12735
Globalize( "en" ).numberParser({ style: "percent" })( "100%" );
// > 1
enParser( "∞" );
// > Infinity
enParser( "-3" );
// > -3
enParser( "-∞" );
// > -Infinity
enParser( "invalid-stuff" );
// > NaN
enParser( "invalid-stuff-that-includes-number-123" );
// > NaN
enParser( "invalid-stuff-123-that-includes-number" );
// > NaN
enParser( "123-invalid-stuff-that-includes-number" );
// > NaN
// Invalid decimal separator. (note `.` is used as decimal separator for English)
enParser( "3,14" );
// > NaN
// Invalid grouping separator position.
enParser( "127,35.00" );
// > NaN
```
Loose matching examples.
```js
var svParser = Globalize( "sv" ).numberParser();
// Swedish uses NO-BREAK-SPACE U+00A0 as grouping separator.
svParser( "1\xA0000,50" );
// > 1000.5
// The parser is lenient and accepts various space characters like regular space
// SPACE U+0020. Technically, it accepts any character of the Unicode general
// category [:Zs:].
svParser( "1 000,50" );
// > 1000.5
var fiParser = Globalize( "fi" ).numberParser();
// Finish uses MINUS SIGN U+2212 for the minus sign.
fiParser( "\u22123" );
// > -3
// The parser is lenient and accepts various hyphen characters like regular
// HYPHEN-MINUS U+002D. Technically, it accepts any character of the Unicode
// general category [:Dash:].
fiParser( "-3" );
// > -3
```
For improved performance on iterations, first create the parser. Then, reuse it
on each loop.
```javascript
var formattedNumbers = [ "1", "1", "2", "3", ... ];
var parser = Globalize( "en" ).numberParser();
numbers = formattedNumbers.map(function( formattedNumber ) {
return parser( formattedNumber );
});
```

View File

@@ -0,0 +1,140 @@
## .numberToPartsFormatter( [options] ) ➜ function( value )
Return a function that formats a number into parts tokens according to the given options.
The returned function is invoked with one argument: the Number `value` to be formatted.
### Parameters
#### options
Please, see [.numberFormatter() options](./number-formatter.md#parameters).
### Returns
An Array of objects containing the formatted number in parts. The returned structure looks like this:
- `decimal`
The decimal separator string, e.g., `"."`.
- `fraction`
The fraction number.
- `group`
The group separator string, e.g., `","`.
- `infinity`
The Infinity string, e.g., `"∞"`.
- `integer`
The integer number.
- `literal`
Any literal strings or whitespace in the formatted number.
- `minusSign`
The minus sign string, e.g., `"-"`.
- `nan`
The NaN string, e.g., `"NaN"`.
- `plusSign`
The plus sign string, e.g., `"+"`.
- `percentSign`
The percent sign string, e.g., `"%"`.
- `compact`
The compact string, e.g., `"thousand"`.
### Examples
Prior to using any number methods, you must load `cldr/main/{locale}/numbers.json` and `cldr/supplemental/numberingSystems.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
#### Static Formatter
You can use the static method `Globalize.numberToPartsFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.numberToPartsFormatter();
formatter( 3.141592 );
// > [
// { "type": "integer", "value": "3" },
// { "type": "decimal", "value": "." },
// { "type": "fraction", "value": "142" }
// ]
```
#### Instance Formatter
You can use the instance method `.numberFormatter()`, which uses the instance
locale.
```javascript
var arFormatter = Globalize( "ar" ).numberToPartsFormatter(),
esFormatter = Globalize( "es" ).numberToPartsFormatter(),
zhFormatter = Globalize( "zh-u-nu-native" ).numberToPartsFormatter();
arFormatter( 3.141592 );
// > [
// { "type": "integer", "value": "٣" },
// { "type": "decimal", "value": "٫" },
// { "type": "fraction", "value": "١٤٢" }
// ]
esFormatter( 3.141592 );
// > [
// { "type": "integer", "value": "3" },
// { "type": "decimal", "value": "," },
// { "type": "fraction", "value": "142" }
// ]
zhFormatter( 3.141592 );
// > [
// { "type": "integer", "value": "三" },
// { "type": "decimal", "value": "." },
// { "type": "fraction", "value": "一四二" }
// ]
```
The information is available separately and it can be formatted and concatenated again in a customized way. For example by using [`Array.prototype.map()`][], [arrow functions][], a [switch statement][], [template literals][], and [`Array.prototype.reduce()`][].
[`Array.prototype.map()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
[arrow functions]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
[switch statement]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
[template literals]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
[`Array.prototype.reduce()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
#### More Examples
Please, see [.numberFormatter() example](./number-formatter.md#example) for additional examples such as configuring decimal places, significant digits, percentages, and compact numbers.
#### Performance Suggestions
For improved performance on iterations, the formatter should be created before the loop. Then, it can be reused in each iteration.
```javascript
var numbers = [ 1, 1, 2, 3, ... ];
var formatter = Globalize( "en" ).numberFormatter();
formattedNumbers = numbers.map(function( number ) {
return formatter( number );
});
```

View File

@@ -0,0 +1,84 @@
## .pluralGenerator( [options] ) ➜ function( value )
It supports the creation of internationalized messages with plural inflection by returning a function that returns the value's plural group: `zero`, `one`, `two`, `few`, `many`, or `other`.
The returned function is invoked with one argument: the Number `value` for which to return the plural group.
### Parameters
#### options.type
Optional. String `cardinal` (default), or `ordinal`.
#### value
A Number for which to return the plural group.
### Example
Prior to using any plural method, you must load either `supplemental/plurals.json` for cardinals or `supplemental/ordinals.json` for ordinals.
Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.pluralGenerator()`, which uses the default locale.
```javascript
var plural;
Globalize.locale( "en" );
// Cardinals
plural = Globalize.pluralGenerator();
plural( 0 );
// > "other"
plural( 1 );
// > "one"
plural( 2 );
// > "other"
// Ordinals
plural = Globalize.pluralGenerator({ type: "ordinal" });
plural( 0 );
// > "other"
plural( 1 );
// > "one"
plural( 2 );
// > "two"
```
You can use the instance method `.pluralGenerator()`, which uses the instance locale.
```javascript
var plural = Globalize( "zh" ).pluralGenerator();
plural( 1 );
// > "other"
```
For comparison (cardinals):
| | en (English) | ru (Russian) | ar (Arabic) |
| ------------- | ------------ | ------------ | ----------- |
| `plural( 0 )` | `other` | `many` | `zero` |
| `plural( 1 )` | `one` | `one` | `one` |
| `plural( 2 )` | `other` | `few` | `two` |
| `plural( 3 )` | `other` | `few` | `few` |
| `plural( 5 )` | `other` | `many` | `few` |
For comparison (ordinals):
| | en (English) | ru (Russian) | ar (Arabic) |
| ---------------------------------- | ------------ | ------------ | ----------- |
| `plural( 0, { type: "ordinal" } )` | `other` | `other` | `other` |
| `plural( 1, { type: "ordinal" } )` | `one` | `other` | `other` |
| `plural( 2, { type: "ordinal" } )` | `two` | `other` | `other` |
| `plural( 3, { type: "ordinal" } )` | `few` | `other` | `other` |
| `plural( 5, { type: "ordinal" } )` | `other` | `other` | `other` |

View File

@@ -0,0 +1,60 @@
## .relativeTimeFormatter( unit [, options] ) ➜ function( value )
Returns a function that formats a relative time according to the given unit, options, and the default/instance locale.
The returned function is invoked with one argument: the number `value` to be formatted.
### Parameters
#### unit
String value indicating the unit to be formatted. eg. "day", "week", "month", etc.
#### options.form
String, e.g., `"short"` or `"narrow"`, or falsy for default long form.
#### value
The number to be formatted.
### Example
Prior to using any relative time methods, you must load `cldr/main/{locale}/dateFields.json` and the CLDR content required by the number and plural modules. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.relativeTimeFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.relativeTimeFormatter( "month" );
formatter( 1 );
// > "next month"
formatter( 3 );
// > "in 3 months"
formatter( -1 );
// > "last month"
formatter( -3 );
// > "3 months ago"
```
You can use the instance method `.relativeTimeFormatter()`, which uses the instance locale.
```javascript
var globalize = new Globalize( "en" ),
formatter = globalize.relativeTimeFormatter( "week" );
formatter( 1 );
// > "next week"
```

View File

@@ -0,0 +1,72 @@
## .unitFormatter( unit [, options] ) ➜ function( value )
Returns a function that formats a unit according to the given unit, options, and the default/instance locale.
The returned function is invoked with one argument: the number `value` to be formatted.
### Parameters
#### unit
String value indicating the unit to be formatted. eg. "day", "week", "month", etc. Could also be a compound unit, eg. "mile-per-hour" or "mile/hour"
#### options.form
Optional. String, e.g., `"long"` (default), `"short"` or `"narrow"`.
#### options.numberFormatter
Optional. A number formatter function. Defaults to `Globalize.numberFormatter()` for the current locale using the default options.
#### value
The number to be formatted.
### Example
Prior to using any unit methods, you must load `cldr/main/{locale}/units.json` and the CLDR content required by the plural module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.unitFormatter()`, which uses the default locale.
```javascript
var customNumberFormatter, formatter;
Globalize.locale( "en" );
formatter = Globalize.unitFormatter( "month", { form: "long" } );
formatter( 1 );
// > "1 month"
formatter( 3 );
// > "3 months"
formatter( 3000 );
// > "3,000 months"
```
You can pass a custom number formatter to format the number of units.
```javascript
var customNumberFormatter, formatter;
Globalize.locale( "en" );
customNumberFormatter = Globalize.numberFormatter({ useGrouping = false })
formatter = Globalize.unitFormatter( "mile-per-hour", {
form: "narrow", numberFormatter: customNumberFormatter
} );
formatter(5000)
// > "5000mph"
```
You can use the instance method `.unitFormatter()`, which uses the instance locale.
```javascript
var globalize = new Globalize( "en" ),
formatter = globalize.unitFormatter( "mile-per-hour", { form: "narrow" } );
formatter( 10 );
// > "10mph"
```