-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFloats.php
More file actions
64 lines (51 loc) · 1.35 KB
/
Floats.php
File metadata and controls
64 lines (51 loc) · 1.35 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
<?php declare(strict_types=1);
namespace h4kuna\DataType\Basic;
use h4kuna\DataType;
use h4kuna\DataType\Exceptions\InvalidTypeException;
use Nette\StaticClass;
use Nette\Utils;
final class Floats
{
use StaticClass;
public static function nullable(mixed $value): ?float
{
return $value === null ? null : self::from($value);
}
public static function from(
mixed $value,
string $decimalPoint = ',',
string $thousandSeparator = ' '
): float
{
if (is_numeric($value) || $value === '' || is_bool($value) || $value === null) {
return (float) $value;
} elseif (is_array($value) || is_object($value)) {
throw InvalidTypeException::invalidFloat($value);
}
assert(is_string($value));
if (Utils\Strings::match($value, '/^\d{1,2}:\d{1,2}(:\d{1,2})?$/') !== null) {
return self::fromHour($value);
}
$out = str_replace([$thousandSeparator, $decimalPoint], ['', '.'], $value);
if (is_numeric($out)) {
return (float) $out;
}
throw InvalidTypeException::invalidFloat($value);
}
/**
* Format HH:MM or HH:MM:SS
*/
public static function fromHour(string $value): float
{
$minus = false;
if (str_starts_with($value, '-')) {
$minus = true;
$value = substr($value, 1);
}
$out = 0.0;
foreach (explode(':', $value) as $i => $v) {
$out += (Integer::from($v) / pow(60, $i));
}
return $minus ? $out * -1 : $out;
}
}