forked from cakephp/i18n
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Number.php
391 lines (349 loc) · 13.9 KB
/
Number.php
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
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 0.10.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\I18n;
use NumberFormatter;
/**
* Number helper library.
*
* Methods to make numbers more readable.
*
* @link http://book.cakephp.org/3.0/en/core-libraries/number.html
*/
class Number
{
/**
* Default locale
*
* @var string
*/
const DEFAULT_LOCALE = 'en_US';
/**
* Format type to format as currency
*
* @var string
*/
const FORMAT_CURRENCY = 'currency';
/**
* A list of number formatters indexed by locale and type
*
* @var array
*/
protected static $_formatters = [];
/**
* Default currency used by Number::currency()
*
* @var string|null
*/
protected static $_defaultCurrency = null;
/**
* Formats a number with a level of precision.
*
* Options:
*
* - `locale`: The locale name to use for formatting the number, e.g. fr_FR
*
* @param float $value A floating point number.
* @param int $precision The precision of the returned number.
* @param array $options Additional options
* @return string Formatted float.
* @link http://book.cakephp.org/3.0/en/core-libraries/number.html#formatting-floating-point-numbers
*/
public static function precision($value, $precision = 3, array $options = [])
{
$formatter = static::formatter(['precision' => $precision, 'places' => $precision] + $options);
return $formatter->format($value);
}
/**
* Returns a formatted-for-humans file size.
*
* @param int $size Size in bytes
* @return string Human readable size
* @link http://book.cakephp.org/3.0/en/core-libraries/number.html#interacting-with-human-readable-values
*/
public static function toReadableSize($size)
{
switch (true) {
case $size < 1024:
return __dn('cake', '{0,number,integer} Byte', '{0,number,integer} Bytes', $size, $size);
case round($size / 1024) < 1024:
return __d('cake', '{0,number,#,###.##} KB', $size / 1024);
case round($size / 1024 / 1024, 2) < 1024:
return __d('cake', '{0,number,#,###.##} MB', $size / 1024 / 1024);
case round($size / 1024 / 1024 / 1024, 2) < 1024:
return __d('cake', '{0,number,#,###.##} GB', $size / 1024 / 1024 / 1024);
default:
return __d('cake', '{0,number,#,###.##} TB', $size / 1024 / 1024 / 1024 / 1024);
}
}
/**
* Formats a number into a percentage string.
*
* Options:
*
* - `multiply`: Multiply the input value by 100 for decimal percentages.
* - `locale`: The locale name to use for formatting the number, e.g. fr_FR
*
* @param float $value A floating point number
* @param int $precision The precision of the returned number
* @param array $options Options
* @return string Percentage string
* @link http://book.cakephp.org/3.0/en/core-libraries/number.html#formatting-percentages
*/
public static function toPercentage($value, $precision = 2, array $options = [])
{
$options += ['multiply' => false];
if ($options['multiply']) {
$value *= 100;
}
return static::precision($value, $precision, $options) . '%';
}
/**
* Formats a number into the correct locale format
*
* Options:
*
* - `places` - Minimum number or decimals to use, e.g 0
* - `precision` - Maximum Number of decimal places to use, e.g. 2
* - `pattern` - An ICU number pattern to use for formatting the number. e.g #,###.00
* - `locale` - The locale name to use for formatting the number, e.g. fr_FR
* - `before` - The string to place before whole numbers, e.g. '['
* - `after` - The string to place after decimal numbers, e.g. ']'
*
* @param float $value A floating point number.
* @param array $options An array with options.
* @return string Formatted number
*/
public static function format($value, array $options = [])
{
$formatter = static::formatter($options);
$options += ['before' => '', 'after' => ''];
return $options['before'] . $formatter->format($value) . $options['after'];
}
/**
* Parse a localized numeric string and transform it in a float point
*
* Options:
*
* - `locale` - The locale name to use for parsing the number, e.g. fr_FR
* - `type` - The formatter type to construct, set it to `currency` if you need to parse
* numbers representing money.
*
* @param string $value A numeric string.
* @param array $options An array with options.
* @return float point number
*/
public static function parseFloat($value, array $options = [])
{
$formatter = static::formatter($options);
return (float)$formatter->parse($value, NumberFormatter::TYPE_DOUBLE);
}
/**
* Formats a number into the correct locale format to show deltas (signed differences in value).
*
* ### Options
*
* - `places` - Minimum number or decimals to use, e.g 0
* - `precision` - Maximum Number of decimal places to use, e.g. 2
* - `locale` - The locale name to use for formatting the number, e.g. fr_FR
* - `before` - The string to place before whole numbers, e.g. '['
* - `after` - The string to place after decimal numbers, e.g. ']'
*
* @param float $value A floating point number
* @param array $options Options list.
* @return string formatted delta
*/
public static function formatDelta($value, array $options = [])
{
$options += ['places' => 0];
$value = number_format($value, $options['places'], '.', '');
$sign = $value > 0 ? '+' : '';
$options['before'] = isset($options['before']) ? $options['before'] . $sign : $sign;
return static::format($value, $options);
}
/**
* Formats a number into a currency format.
*
* ### Options
*
* - `locale` - The locale name to use for formatting the number, e.g. fr_FR
* - `fractionSymbol` - The currency symbol to use for fractional numbers.
* - `fractionPosition` - The position the fraction symbol should be placed
* valid options are 'before' & 'after'.
* - `before` - Text to display before the rendered number
* - `after` - Text to display after the rendered number
* - `zero` - The text to use for zero values, can be a string or a number. e.g. 0, 'Free!'
* - `places` - Number of decimal places to use. e.g. 2
* - `precision` - Maximum Number of decimal places to use, e.g. 2
* - `pattern` - An ICU number pattern to use for formatting the number. e.g #,###.00
* - `useIntlCode` - Whether or not to replace the currency symbol with the international
* currency code.
*
* @param float $value Value to format.
* @param string|null $currency International currency name such as 'USD', 'EUR', 'JPY', 'CAD'
* @param array $options Options list.
* @return string Number formatted as a currency.
*/
public static function currency($value, $currency = null, array $options = [])
{
$value = (float)$value;
$currency = $currency ?: static::defaultCurrency();
if (isset($options['zero']) && !$value) {
return $options['zero'];
}
$formatter = static::formatter(['type' => static::FORMAT_CURRENCY] + $options);
$abs = abs($value);
if (!empty($options['fractionSymbol']) && $abs > 0 && $abs < 1) {
$value = $value * 100;
$pos = isset($options['fractionPosition']) ? $options['fractionPosition'] : 'after';
return static::format($value, ['precision' => 0, $pos => $options['fractionSymbol']]);
}
$before = isset($options['before']) ? $options['before'] : null;
$after = isset($options['after']) ? $options['after'] : null;
return $before . $formatter->formatCurrency($value, $currency) . $after;
}
/**
* Getter/setter for default currency
*
* @param string|bool|null $currency Default currency string to be used by currency()
* if $currency argument is not provided. If boolean false is passed, it will clear the
* currently stored value
* @return string Currency
*/
public static function defaultCurrency($currency = null)
{
if (!empty($currency)) {
return self::$_defaultCurrency = $currency;
}
if ($currency === false) {
return self::$_defaultCurrency = null;
}
if (empty(self::$_defaultCurrency)) {
$locale = ini_get('intl.default_locale') ?: static::DEFAULT_LOCALE;
$formatter = new NumberFormatter($locale, NumberFormatter::CURRENCY);
self::$_defaultCurrency = $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE);
}
return self::$_defaultCurrency;
}
/**
* Returns a formatter object that can be reused for similar formatting task
* under the same locale and options. This is often a speedier alternative to
* using other methods in this class as only one formatter object needs to be
* constructed.
*
* ### Options
*
* - `locale` - The locale name to use for formatting the number, e.g. fr_FR
* - `type` - The formatter type to construct, set it to `currency` if you need to format
* numbers representing money or a NumberFormatter constant.
* - `places` - Number of decimal places to use. e.g. 2
* - `precision` - Maximum Number of decimal places to use, e.g. 2
* - `pattern` - An ICU number pattern to use for formatting the number. e.g #,###.00
* - `useIntlCode` - Whether or not to replace the currency symbol with the international
* currency code.
*
* @param array $options An array with options.
* @return \NumberFormatter The configured formatter instance
*/
public static function formatter($options = [])
{
$locale = isset($options['locale']) ? $options['locale'] : ini_get('intl.default_locale');
if (!$locale) {
$locale = static::DEFAULT_LOCALE;
}
$type = NumberFormatter::DECIMAL;
if (!empty($options['type'])) {
$type = $options['type'];
if ($options['type'] === static::FORMAT_CURRENCY) {
$type = NumberFormatter::CURRENCY;
}
}
if (!isset(static::$_formatters[$locale][$type])) {
static::$_formatters[$locale][$type] = new NumberFormatter($locale, $type);
}
$formatter = static::$_formatters[$locale][$type];
$options = array_intersect_key($options, [
'places' => null,
'precision' => null,
'pattern' => null,
'useIntlCode' => null
]);
if (empty($options)) {
return $formatter;
}
$formatter = clone $formatter;
return static::_setAttributes($formatter, $options);
}
/**
* Configure formatters.
*
* @param string $locale The locale name to use for formatting the number, e.g. fr_FR
* @param int $type The formatter type to construct. Defaults to NumberFormatter::DECIMAL.
* @param array $options See Number::formatter() for possible options.
* @return void
*/
public static function config($locale, $type = NumberFormatter::DECIMAL, array $options = [])
{
static::$_formatters[$locale][$type] = static::_setAttributes(
new NumberFormatter($locale, $type),
$options
);
}
/**
* Set formatter attributes
*
* @param \NumberFormatter $formatter Number formatter instance.
* @param array $options See Number::formatter() for possible options.
* @return \NumberFormatter
*/
protected static function _setAttributes(NumberFormatter $formatter, array $options = [])
{
if (isset($options['places'])) {
$formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $options['places']);
}
if (isset($options['precision'])) {
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $options['precision']);
}
if (!empty($options['pattern'])) {
$formatter->setPattern($options['pattern']);
}
if (!empty($options['useIntlCode'])) {
// One of the odd things about ICU is that the currency marker in patterns
// is denoted with ¤, whereas the international code is marked with ¤¤,
// in order to use the code we need to simply duplicate the character wherever
// it appears in the pattern.
$pattern = trim(str_replace('¤', '¤¤ ', $formatter->getPattern()));
$formatter->setPattern($pattern);
}
return $formatter;
}
/**
* Returns a formatted integer as an ordinal number string (e.g. 1st, 2nd, 3rd, 4th, [...])
*
* ### Options
*
* - `type` - The formatter type to construct, set it to `currency` if you need to format
* numbers representing money or a NumberFormatter constant.
*
* For all other options see formatter().
*
* @param int|float $value An integer
* @param array $options An array with options.
* @return string
*/
public static function ordinal($value, array $options = [])
{
return static::formatter(['type' => NumberFormatter::ORDINAL] + $options)->format($value);
}
}