forked from kornrunner/CLDR
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberFormatter.php
More file actions
74 lines (62 loc) · 2 KB
/
NumberFormatter.php
File metadata and controls
74 lines (62 loc) · 2 KB
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
<?php
/*
* This file is part of the ICanBoogie package.
*
* (c) Olivier Laviale <olivier.laviale@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ICanBoogie\CLDR;
use ICanBoogie\CLDR\Numbers\Symbols;
/**
* A number formatter.
*/
class NumberFormatter implements Formatter
{
/**
* Format 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 $number The number to be formatted.
* @param string $pattern The pattern used to format the number.
*/
public function __invoke($number, string $pattern, ?Symbols $symbols = null): string
{
return $this->format($number, $pattern, $symbols);
}
/**
* Format 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 $number The number to be formatted.
* @param string|NumberPattern $pattern The pattern used to format the number.
*/
public function format($number, $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,
]);
}
}