/
number_pipe.ts
315 lines (297 loc) Β· 11.1 KB
/
number_pipe.ts
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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {DEFAULT_CURRENCY_CODE, Inject, LOCALE_ID, Pipe, PipeTransform} from '@angular/core';
import {formatCurrency, formatNumber, formatPercent} from '../i18n/format_number';
import {getCurrencySymbol} from '../i18n/locale_data_api';
import {invalidPipeArgumentError} from './invalid_pipe_argument_error';
/**
* @ngModule CommonModule
* @description
*
* Formats a value according to digit options and locale rules.
* Locale determines group sizing and separator,
* decimal point character, and other locale-specific configurations.
*
* @see `formatNumber()`
*
* @usageNotes
*
* ### digitsInfo
*
* The value's decimal representation is specified by the `digitsInfo`
* parameter, written in the following format:<br>
*
* ```
* {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
* ```
*
* - `minIntegerDigits`:
* The minimum number of integer digits before the decimal point.
* Default is 1.
*
* - `minFractionDigits`:
* The minimum number of digits after the decimal point.
* Default is 0.
*
* - `maxFractionDigits`:
* The maximum number of digits after the decimal point.
* Default is 3.
*
* If the formatted value is truncated it will be rounded using the "to-nearest" method:
*
* ```
* {{3.6 | number: '1.0-0'}}
* <!--will output '4'-->
*
* {{-3.6 | number:'1.0-0'}}
* <!--will output '-4'-->
* ```
*
* ### locale
*
* `locale` will format a value according to locale rules.
* Locale determines group sizing and separator,
* decimal point character, and other locale-specific configurations.
*
* When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.
*
* See [Setting your app locale](guide/i18n-common-locale-id).
*
* ### Example
*
* The following code shows how the pipe transforms values
* according to various format specifications,
* where the caller's default locale is `en-US`.
*
* <code-example path="common/pipes/ts/number_pipe.ts" region='NumberPipe'></code-example>
*
* @publicApi
*/
@Pipe({
name: 'number',
standalone: true,
})
export class DecimalPipe implements PipeTransform {
constructor(@Inject(LOCALE_ID) private _locale: string) {}
transform(value: number|string, digitsInfo?: string, locale?: string): string|null;
transform(value: null|undefined, digitsInfo?: string, locale?: string): null;
transform(value: number|string|null|undefined, digitsInfo?: string, locale?: string): string|null;
/**
* @param value The value to be formatted.
* @param digitsInfo Sets digit and decimal representation.
* [See more](#digitsinfo).
* @param locale Specifies what locale format rules to use.
* [See more](#locale).
*/
transform(value: number|string|null|undefined, digitsInfo?: string, locale?: string): string
|null {
if (!isValue(value)) return null;
locale = locale || this._locale;
try {
const num = strToNumber(value);
return formatNumber(num, locale, digitsInfo);
} catch (error) {
throw invalidPipeArgumentError(DecimalPipe, (error as Error).message);
}
}
}
/**
* @ngModule CommonModule
* @description
*
* Transforms a number to a percentage
* string, formatted according to locale rules that determine group sizing and
* separator, decimal-point character, and other locale-specific
* configurations.
*
* @see `formatPercent()`
*
* @usageNotes
* The following code shows how the pipe transforms numbers
* into text strings, according to various format specifications,
* where the caller's default locale is `en-US`.
*
* <code-example path="common/pipes/ts/percent_pipe.ts" region='PercentPipe'></code-example>
*
* @publicApi
*/
@Pipe({
name: 'percent',
standalone: true,
})
export class PercentPipe implements PipeTransform {
constructor(@Inject(LOCALE_ID) private _locale: string) {}
transform(value: number|string, digitsInfo?: string, locale?: string): string|null;
transform(value: null|undefined, digitsInfo?: string, locale?: string): null;
transform(value: number|string|null|undefined, digitsInfo?: string, locale?: string): string|null;
/**
*
* @param value The number to be formatted as a percentage.
* @param digitsInfo Decimal representation options, specified by a string
* in the following format:<br>
* <code>{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</code>.
* - `minIntegerDigits`: The minimum number of integer digits before the decimal point.
* Default is `1`.
* - `minFractionDigits`: The minimum number of digits after the decimal point.
* Default is `0`.
* - `maxFractionDigits`: The maximum number of digits after the decimal point.
* Default is `0`.
* @param locale A locale code for the locale format rules to use.
* When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.
* See [Setting your app locale](guide/i18n-common-locale-id).
*/
transform(value: number|string|null|undefined, digitsInfo?: string, locale?: string): string
|null {
if (!isValue(value)) return null;
locale = locale || this._locale;
try {
const num = strToNumber(value);
return formatPercent(num, locale, digitsInfo);
} catch (error) {
throw invalidPipeArgumentError(PercentPipe, (error as Error).message);
}
}
}
/**
* @ngModule CommonModule
* @description
*
* Transforms a number to a currency string, formatted according to locale rules
* that determine group sizing and separator, decimal-point character,
* and other locale-specific configurations.
*
* {@a currency-code-deprecation}
* <div class="alert is-helpful">
*
* **Deprecation notice:**
*
* The default currency code is currently always `USD` but this is deprecated from v9.
*
* **In v11 the default currency code will be taken from the current locale identified by
* the `LOCALE_ID` token. See the [i18n guide](guide/i18n-common-locale-id) for
* more information.**
*
* If you need the previous behavior then set it by creating a `DEFAULT_CURRENCY_CODE` provider in
* your application `NgModule`:
*
* ```ts
* {provide: DEFAULT_CURRENCY_CODE, useValue: 'USD'}
* ```
*
* </div>
*
* @see `getCurrencySymbol()`
* @see `formatCurrency()`
*
* @usageNotes
* The following code shows how the pipe transforms numbers
* into text strings, according to various format specifications,
* where the caller's default locale is `en-US`.
*
* <code-example path="common/pipes/ts/currency_pipe.ts" region='CurrencyPipe'></code-example>
*
* @publicApi
*/
@Pipe({
name: 'currency',
standalone: true,
})
export class CurrencyPipe implements PipeTransform {
constructor(
@Inject(LOCALE_ID) private _locale: string,
@Inject(DEFAULT_CURRENCY_CODE) private _defaultCurrencyCode: string = 'USD') {}
transform(
value: number|string, currencyCode?: string,
display?: 'code'|'symbol'|'symbol-narrow'|string|boolean, digitsInfo?: string,
locale?: string): string|null;
transform(
value: null|undefined, currencyCode?: string,
display?: 'code'|'symbol'|'symbol-narrow'|string|boolean, digitsInfo?: string,
locale?: string): null;
transform(
value: number|string|null|undefined, currencyCode?: string,
display?: 'code'|'symbol'|'symbol-narrow'|string|boolean, digitsInfo?: string,
locale?: string): string|null;
/**
*
* @param value The number to be formatted as currency.
* @param currencyCode The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code,
* such as `USD` for the US dollar and `EUR` for the euro. The default currency code can be
* configured using the `DEFAULT_CURRENCY_CODE` injection token.
* @param display The format for the currency indicator. One of the following:
* - `code`: Show the code (such as `USD`).
* - `symbol`(default): Show the symbol (such as `$`).
* - `symbol-narrow`: Use the narrow symbol for locales that have two symbols for their
* currency.
* For example, the Canadian dollar CAD has the symbol `CA$` and the symbol-narrow `$`. If the
* locale has no narrow symbol, uses the standard symbol for the locale.
* - String: Use the given string value instead of a code or a symbol.
* For example, an empty string will suppress the currency & symbol.
* - Boolean (marked deprecated in v5): `true` for symbol and false for `code`.
*
* @param digitsInfo Decimal representation options, specified by a string
* in the following format:<br>
* <code>{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</code>.
* - `minIntegerDigits`: The minimum number of integer digits before the decimal point.
* Default is `1`.
* - `minFractionDigits`: The minimum number of digits after the decimal point.
* Default is `2`.
* - `maxFractionDigits`: The maximum number of digits after the decimal point.
* Default is `2`.
* If not provided, the number will be formatted with the proper amount of digits,
* depending on what the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) specifies.
* For example, the Canadian dollar has 2 digits, whereas the Chilean peso has none.
* @param locale A locale code for the locale format rules to use.
* When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.
* See [Setting your app locale](guide/i18n-common-locale-id).
*/
transform(
value: number|string|null|undefined, currencyCode: string = this._defaultCurrencyCode,
display: 'code'|'symbol'|'symbol-narrow'|string|boolean = 'symbol', digitsInfo?: string,
locale?: string): string|null {
if (!isValue(value)) return null;
locale = locale || this._locale;
if (typeof display === 'boolean') {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && <any>console && <any>console.warn) {
console.warn(
`Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are "code", "symbol" or "symbol-narrow".`);
}
display = display ? 'symbol' : 'code';
}
let currency: string = currencyCode || this._defaultCurrencyCode;
if (display !== 'code') {
if (display === 'symbol' || display === 'symbol-narrow') {
currency = getCurrencySymbol(currency, display === 'symbol' ? 'wide' : 'narrow', locale);
} else {
currency = display;
}
}
try {
const num = strToNumber(value);
return formatCurrency(num, locale, currency, currencyCode, digitsInfo);
} catch (error) {
throw invalidPipeArgumentError(CurrencyPipe, (error as Error).message);
}
}
}
function isValue(value: number|string|null|undefined): value is number|string {
return !(value == null || value === '' || value !== value);
}
/**
* Transforms a string into a number (if needed).
*/
function strToNumber(value: number|string): number {
// Convert strings to numbers
if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) {
return Number(value);
}
if (typeof value !== 'number') {
throw new Error(`${value} is not a number`);
}
return value;
}