1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yiisoft\Strings; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Provides static methods to work with numeric strings. |
7
|
|
|
*/ |
8
|
|
|
final class NumericHelper |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Converts number to its ordinal English form. For example, converts 13 to 13th, 2 to 2nd ... |
12
|
|
|
* @param int $number The number to get its ordinal value. |
13
|
|
|
* @return string |
14
|
|
|
*/ |
15
|
1 |
|
public static function toOrdinal(int $number): ?string |
16
|
|
|
{ |
17
|
1 |
|
if (\in_array($number % 100, range(11, 13), true)) { |
18
|
1 |
|
return $number . 'th'; |
19
|
|
|
} |
20
|
1 |
|
switch ($number % 10) { |
21
|
1 |
|
case 1: |
22
|
1 |
|
return $number . 'st'; |
23
|
1 |
|
case 2: |
24
|
1 |
|
return $number . 'nd'; |
25
|
1 |
|
case 3: |
26
|
1 |
|
return $number . 'rd'; |
27
|
|
|
default: |
28
|
1 |
|
return $number . 'th'; |
29
|
|
|
} |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Returns string representation of number value with replaced commas to dots, if decimal point |
34
|
|
|
* of current locale is comma. |
35
|
|
|
* @param int|float|string $value |
36
|
|
|
* @return string |
37
|
|
|
*/ |
38
|
|
|
public static function normalizeNumber($value): string |
39
|
|
|
{ |
40
|
|
|
$value = (string)$value; |
41
|
|
|
|
42
|
|
|
$localeInfo = localeconv(); |
43
|
|
|
$decimalSeparator = $localeInfo['decimal_point'] ?? null; |
44
|
|
|
|
45
|
|
|
if ($decimalSeparator !== null && $decimalSeparator !== '.') { |
46
|
|
|
$value = str_replace($decimalSeparator, '.', $value); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return $value; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Safely casts a float to string independent of the current locale. |
54
|
|
|
* |
55
|
|
|
* The decimal separator will always be `.`. |
56
|
|
|
* @param float|int $number A floating point number or integer. |
57
|
|
|
* @return string The string representation of the number. |
58
|
|
|
*/ |
59
|
1 |
|
public static function floatToString($number): string |
60
|
|
|
{ |
61
|
|
|
// . and , are the only decimal separators known in ICU data, |
62
|
|
|
// so its safe to call str_replace here |
63
|
1 |
|
return str_replace(',', '.', (string)$number); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|