Skip to content

Commit

Permalink
Convert non finite floats 'INF', '-INF', and 'NAN' strings to floats.
Browse files Browse the repository at this point in the history
  • Loading branch information
prwater committed May 10, 2020
1 parent c2eb09b commit a26ed4c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
34 changes: 31 additions & 3 deletions src/Cast.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,39 @@ public static function isManBool($value): bool

//--------------------------------------------------------------------------------------------------------------------
/**
* Returns true if and only if a value is not null and can be casted to a finite float. Otherwise returns false.
* Returns true if and only if a value is not null and can be casted to a float. Otherwise returns false.
*
* @param mixed $value The value.
*
* @return bool
*/
public static function isManFiniteFloat($value): bool
{
return (static::isManFloat($value) && is_finite((float)$value));
switch (gettype($value))
{
case 'boolean':
case 'integer':
return true;

case 'double':
return is_finite($value);

case 'string':
// Reject empty strings.
if ($value==='') return false;

// Reject leading zeros unless they are followed by a decimal point
if (strlen($value)>1 && $value[0]==='0' && $value[1]!=='.') return false;

$filtered = filter_var($value,
FILTER_SANITIZE_NUMBER_FLOAT,
FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_SCIENTIFIC);

return ($filtered===$value);

default:
return false;
}
}

//--------------------------------------------------------------------------------------------------------------------
Expand Down Expand Up @@ -72,7 +96,7 @@ public static function isManFloat($value): bool
FILTER_SANITIZE_NUMBER_FLOAT,
FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_SCIENTIFIC);

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

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

if ($value==='NAN') return NAN;
if ($value==='INF') return INF;
if ($value==='-INF') return -INF;

return (float)$value;
}

Expand Down
6 changes: 6 additions & 0 deletions test/CastFloatTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,12 @@ public function validManFloatCases(): array
['value' => -INF,
'expected' => -INF],
['value' => NAN,
'expected' => NAN],
['value' => 'INF',
'expected' => INF],
['value' => '-INF',
'expected' => -INF],
['value' => 'NAN',
'expected' => NAN]];
}

Expand Down

0 comments on commit a26ed4c

Please sign in to comment.