You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Includes formatters that perform unit promotion. We DO NOT do
unit conversion (for example, inches to centimeters), we only
choose within the appropriate system (metric or imperial) the
best representation for a given value.
For example, saying `10cm` is much better than saying `0.1m`.
Both are still within the metric system.
Considerations made during this change:
- We only use unit symbols, not the full names. This simplifies
aspects such as translations, since most units are universal
but their localized full names are not. There is some space
for later accepting full names (new MetricFormatter('meter'))
and deciding the output representation automatically. This is
also the reason why PHP enums were not used as the source of
truth for supported units.
- Time unit symbols are *not universal*, but they were considered
for inclusion for their value in technical systems (simplifying
a log entry or measure).
- The SI (colloquially known as "metric system") is the widest
adopted standard, so only "Imperial" was prefixed. We used the
"Metric" name to denote SI Length units.
The `MetricFormatter` promotes metric *length* values between `mm`, `cm`, `m`, and `km`.
11
+
12
+
- Non-numeric input is returned unchanged.
13
+
- Promotion is based on magnitude.
14
+
- Output uses symbols only (no spaces), e.g. `1km`, `10cm`.
15
+
16
+
## Usage
17
+
18
+
```php
19
+
use Respect\StringFormatter\MetricFormatter;
20
+
21
+
$formatter = new MetricFormatter('m');
22
+
23
+
echo $formatter->format('1000');
24
+
// Outputs: 1km
25
+
26
+
echo $formatter->format('0.1');
27
+
// Outputs: 10cm
28
+
```
29
+
30
+
## API
31
+
32
+
### `MetricFormatter::__construct`
33
+
34
+
-`__construct(string $unit = 'm')`
35
+
36
+
The `$unit` is the input unit (the unit you are providing values in).
37
+
38
+
Accepted units: `mm`, `cm`, `m`, `km`.
39
+
40
+
### `format`
41
+
42
+
-`format(string $input): string`
43
+
44
+
If the input is numeric, it is promoted to the closest appropriate metric scale and returned with the corresponding symbol.
45
+
46
+
## Behavior
47
+
48
+
### Promotion rule
49
+
50
+
The formatter chooses a unit where the promoted value is in the range $[1, 1000)$ when possible. If not possible, it uses the smallest (`mm`) or largest (`km`) unit as needed.
51
+
52
+
### No rounding
53
+
54
+
Values are not rounded. Trailing fractional zeros are trimmed:
0 commit comments