1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Strings; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Provides static methods to work with numeric strings. |
9
|
|
|
*/ |
10
|
|
|
final class NumericHelper |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Converts number to its ordinal English form. For example, converts 13 to 13th, 2 to 2nd etc. |
14
|
|
|
* |
15
|
|
|
* @param float|int|string $value The number to get its ordinal value. |
16
|
|
|
* |
17
|
|
|
* @return string |
18
|
|
|
*/ |
19
|
2 |
|
public static function toOrdinal($value): string |
20
|
|
|
{ |
21
|
2 |
|
if (!is_numeric($value)) { |
22
|
1 |
|
$type = gettype($value); |
23
|
1 |
|
throw new \InvalidArgumentException("Value must be numeric. $type given."); |
24
|
|
|
} |
25
|
|
|
|
26
|
1 |
|
if (fmod((float)$value, 1) !== 0.00) { |
27
|
1 |
|
return (string)$value; |
28
|
|
|
} |
29
|
|
|
|
30
|
1 |
|
if (\in_array($value % 100, [11, 12, 13], true)) { |
31
|
1 |
|
return $value . 'th'; |
32
|
|
|
} |
33
|
1 |
|
switch ($value % 10) { |
34
|
1 |
|
case 1: |
35
|
1 |
|
return $value . 'st'; |
36
|
1 |
|
case 2: |
37
|
1 |
|
return $value . 'nd'; |
38
|
1 |
|
case 3: |
39
|
1 |
|
return $value . 'rd'; |
40
|
|
|
default: |
41
|
1 |
|
return $value . 'th'; |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Returns string representation of a number value without thousands separators and with dot as decimal separator. |
47
|
|
|
* |
48
|
|
|
* @param float|int|string $value |
49
|
|
|
* |
50
|
|
|
* @return string |
51
|
|
|
*/ |
52
|
8 |
|
public static function normalize($value): string |
53
|
|
|
{ |
54
|
|
|
/** |
55
|
|
|
* @psalm-suppress DocblockTypeContradiction |
56
|
|
|
*/ |
57
|
8 |
|
if (!is_scalar($value)) { |
|
|
|
|
58
|
1 |
|
$type = gettype($value); |
59
|
1 |
|
throw new \InvalidArgumentException("Value must be scalar. $type given."); |
60
|
|
|
} |
61
|
7 |
|
$value = str_replace([' ', ','], ['', '.'], (string)$value); |
62
|
7 |
|
return preg_replace('/\.(?=.*\.)/', '', $value); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Checks whether the given string is an integer number. |
67
|
|
|
*/ |
68
|
|
|
public static function isInteger($value): bool |
69
|
|
|
{ |
70
|
|
|
return filter_var($value, FILTER_VALIDATE_INT); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|