Skip to content

Commit

Permalink
allow exponential float format, closes #1
Browse files Browse the repository at this point in the history
  • Loading branch information
ntzm committed Jun 22, 2019
1 parent 996712d commit b4fb754
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 5 deletions.
3 changes: 2 additions & 1 deletion src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ function toInt($value): int {

/** @throws Uncastable */
function stringToFloat(string $string): float {
if (preg_match('/^-?\d+(\.\d+)?$/', $string) === 1) {
// is_numeric allows leading whitespace, but we don't want to allow that
if (is_numeric($string) && ! ctype_space($string[0] ?? null)) {
return (float) $string;
}

Expand Down
8 changes: 6 additions & 2 deletions tests/StringToFloatTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ public function provideCastable(): Generator
yield [2.0, '2'];
yield [-5.0, '-5'];
yield [0.0, '0'];
yield [0.1, '.1'];
yield [1.0, '1.'];
yield [1.2e3, '1.2e3'];
yield [7E-10, '7E-10'];
}

/** @dataProvider provideUncastable */
Expand All @@ -41,7 +45,7 @@ public function provideUncastable(): Generator
yield [' 1.1 '];
yield ['1.1 '];
yield ['1.1.1'];
yield ['1.'];
yield ['.1'];
yield ['0xf4c3b00c'];
yield ['0b10100111001'];
}
}
8 changes: 6 additions & 2 deletions tests/ToFloatTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ public function provideCastable(): Generator
yield [5.0, 5];
yield [0.0, []];
yield [1.0, ['hello']];
yield [0.1, '.1'];
yield [1.0, '1.'];
yield [1.2e3, '1.2e3'];
yield [7E-10, '7E-10'];
}

/** @dataProvider provideUncastable */
Expand All @@ -47,7 +51,7 @@ public function provideUncastable(): Generator
yield [' 1.1 '];
yield ['1.1 '];
yield ['1.1.1'];
yield ['1.'];
yield ['.1'];
yield ['0xf4c3b00c'];
yield ['0b10100111001'];
}
}

0 comments on commit b4fb754

Please # to comment.