Skip to content

Commit fb69e12

Browse files
committed
fix abs
1 parent 7ebee2b commit fb69e12

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

src/Simple/BCMath.php

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,11 +111,17 @@ public function round($number, int $precision = 0): string
111111
*/
112112
public function abs($number): string
113113
{
114-
if ($this->isNegative($number)) {
115-
return substr($number, 1);
116-
}
114+
try {
115+
$this->add($number, 0); // validator
116+
if ($this->isNegative($number)) {
117+
return substr($number, 1);
118+
}
117119

118-
return $number;
120+
return $number;
121+
} catch (\Throwable $throwable) {
122+
// this is not a number
123+
return 0;
124+
}
119125
}
120126

121127
/**

tests/MathTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ public function testAbs(string $class): void
2121
*/
2222
$provider = app($class);
2323

24+
// not number
25+
$this->assertEquals($provider->abs('hello'), 0);
26+
$this->assertEquals($provider->abs('--121'), 0);
27+
$this->assertEquals($provider->abs('---121'), 0);
28+
2429
// int
2530
$this->assertEquals($provider->abs(123), 123);
2631
$this->assertEquals($provider->abs(-123), 123);

0 commit comments

Comments
 (0)