Skip to content

Commit bccdd3f

Browse files
authored
Merge pull request #194 from bizurkur/improve-floating-point-comparison
Use epsilon to compare floating points
2 parents e69a504 + 333ab35 commit bccdd3f

File tree

3 files changed

+7
-5
lines changed

3 files changed

+7
-5
lines changed

composer.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
},
2323
"require": {
2424
"php": ">=7.2",
25-
"ext-bcmath": "*",
2625
"ext-json": "*",
2726
"devizzent/cebe-php-openapi": "^1.0",
2827
"league/uri": "^6.3",

src/Schema/Keywords/MultipleOf.php

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,14 @@
1010
use Respect\Validation\Validator;
1111
use Throwable;
1212

13-
use function bcdiv;
1413
use function class_exists;
14+
use function round;
1515
use function sprintf;
1616

1717
class MultipleOf extends BaseKeyword
1818
{
19+
private const EPSILON = 0.00000001;
20+
1921
/**
2022
* The value of "multipleOf" MUST be a number, strictly greater than 0.
2123
* A numeric instance is only valid if division by this keyword's value results in an integer.
@@ -39,9 +41,9 @@ public function validate($data, $multipleOf): void
3941
throw InvalidSchema::becauseDefensiveSchemaValidationFailed($e);
4042
}
4143

42-
$value = (float) bcdiv((string) $data, (string) $multipleOf, 1);
43-
if ($value - (int) $value !== 0.0) {
44-
throw KeywordMismatch::fromKeyword('multipleOf', $data, sprintf('Division by %d did not resulted in integer', $multipleOf));
44+
$value = round($data / $multipleOf, 8);
45+
if ($value - (int) $value > self::EPSILON) {
46+
throw KeywordMismatch::fromKeyword('multipleOf', $data, sprintf('Division by %s did not resulted in integer', $multipleOf));
4547
}
4648
}
4749
}

tests/Schema/Keywords/MultipleOfTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ public function invalidDatasets(): array
3535
[10, .11],
3636
[9.9, .451],
3737
[.94, .03],
38+
[1, .3333333],
3839
];
3940
}
4041

0 commit comments

Comments
 (0)