-
Notifications
You must be signed in to change notification settings - Fork 4
/
NumberFormatter.php
61 lines (50 loc) · 1.82 KB
/
NumberFormatter.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
<?php
namespace ICanBoogie\CLDR\Numbers;
use ICanBoogie\CLDR\Core\Formatter;
use ICanBoogie\CLDR\Core\Locale;
use ICanBoogie\CLDR\Core\Localizable;
/**
* A number formatter.
*
* @implements Localizable<NumberFormatter, NumberFormatterLocalized>
*/
final class NumberFormatter implements Formatter, Localizable
{
/**
* Formats a number with the specified pattern.
*
* Note, if the pattern contains '%', the number will be multiplied by 100 first. If the
* pattern contains '‰', the number will be multiplied by 1000.
*
* @param float|int|numeric-string $number
* The number to format.
* @param string|NumberPattern $pattern
* The pattern used to format the number.
*/
public function format(
float|int|string $number,
NumberPattern|string $pattern,
Symbols $symbols = null,
): string {
if (!$pattern instanceof NumberPattern) {
$pattern = NumberPattern::from($pattern);
}
$symbols = $symbols ?? Symbols::defaults();
[ $integer, $decimal ] = $pattern->parse_number($number);
$formatted_integer = $pattern->format_integer_with_group($integer, $symbols->group);
$formatted_number = $pattern->format_integer_with_decimal($formatted_integer, $decimal, $symbols->decimal);
if ($number < 0) {
$number = $pattern->negative_prefix . $formatted_number . $pattern->negative_suffix;
} else {
$number = $pattern->positive_prefix . $formatted_number . $pattern->positive_suffix;
}
return strtr($number, [
'%' => $symbols->percentSign,
'‰' => $symbols->perMille,
]);
}
public function localized(Locale $locale): NumberFormatterLocalized
{
return new NumberFormatterLocalized($this, $locale);
}
}