Skip to content

Commit a26ed4c

Browse files
committed
Convert non finite floats 'INF', '-INF', and 'NAN' strings to floats.
1 parent c2eb09b commit a26ed4c

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

src/Cast.php

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,39 @@ public static function isManBool($value): bool
3333

3434
//--------------------------------------------------------------------------------------------------------------------
3535
/**
36-
* Returns true if and only if a value is not null and can be casted to a finite float. Otherwise returns false.
36+
* Returns true if and only if a value is not null and can be casted to a float. Otherwise returns false.
3737
*
3838
* @param mixed $value The value.
3939
*
4040
* @return bool
4141
*/
4242
public static function isManFiniteFloat($value): bool
4343
{
44-
return (static::isManFloat($value) && is_finite((float)$value));
44+
switch (gettype($value))
45+
{
46+
case 'boolean':
47+
case 'integer':
48+
return true;
49+
50+
case 'double':
51+
return is_finite($value);
52+
53+
case 'string':
54+
// Reject empty strings.
55+
if ($value==='') return false;
56+
57+
// Reject leading zeros unless they are followed by a decimal point
58+
if (strlen($value)>1 && $value[0]==='0' && $value[1]!=='.') return false;
59+
60+
$filtered = filter_var($value,
61+
FILTER_SANITIZE_NUMBER_FLOAT,
62+
FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_SCIENTIFIC);
63+
64+
return ($filtered===$value);
65+
66+
default:
67+
return false;
68+
}
4569
}
4670

4771
//--------------------------------------------------------------------------------------------------------------------
@@ -72,7 +96,7 @@ public static function isManFloat($value): bool
7296
FILTER_SANITIZE_NUMBER_FLOAT,
7397
FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_SCIENTIFIC);
7498

75-
return ($filtered===$value);
99+
return ($filtered===$value || in_array($value, ['NAN', 'INF', '-INF'], true));
76100

77101
default:
78102
return false;
@@ -291,6 +315,10 @@ public static function toManFloat($value, ?float $default = null): float
291315
throw new InvalidCastException('Value can not be converted to float');
292316
}
293317

318+
if ($value==='NAN') return NAN;
319+
if ($value==='INF') return INF;
320+
if ($value==='-INF') return -INF;
321+
294322
return (float)$value;
295323
}
296324

test/CastFloatTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,12 @@ public function validManFloatCases(): array
219219
['value' => -INF,
220220
'expected' => -INF],
221221
['value' => NAN,
222+
'expected' => NAN],
223+
['value' => 'INF',
224+
'expected' => INF],
225+
['value' => '-INF',
226+
'expected' => -INF],
227+
['value' => 'NAN',
222228
'expected' => NAN]];
223229
}
224230

0 commit comments

Comments
 (0)