8000 [Validator] Fix precision issue regarding floats and DivisibleBy cons… · symfony/symfony@ae04b48 · GitHub
[go: up one dir, main page]

Skip to content

Commit ae04b48

Browse files
Jannik Zschieschenicolas-grekas
Jannik Zschiesche
authored andcommitted
[Validator] Fix precision issue regarding floats and DivisibleBy constraint
1 parent 71794f4 commit ae04b48

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

src/Symfony/Component/Validator/Constraints/DivisibleByValidator.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,17 @@ class DivisibleByValidator extends AbstractComparisonValidator
2323
*/
2424
protected function compareValues($value1, $value2)
2525
{
26-
return (float) 0 === fmod($value1, $value2);
26+
if (!$value2 = abs($value2)) {
27+
return false;
28+
}
29+
if (\is_int($value1 = abs($value1)) && \is_int($value2)) {
30+
return 0 === ($value1 % $value2);
31+
}
32+
if (!$remainder = fmod($value1, $value2)) {
33+
return true;
34+
}
35+
36+
return sprintf('%.12e', $value2) === sprintf('%.12e', $remainder);
2737
}
2838

2939
/**

src/Symfony/Component/Validator/Tests/Constraints/DivisibleByValidatorTest.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ public function provideValidComparisons()
4646
array(42, 21),
4747
array(3.25, 0.25),
4848
array('100', '10'),
49+
array(4.1, 0.1),
50+
array(-4.1, 0.1),
4951
);
5052
}
5153

@@ -69,6 +71,7 @@ public function provideInvalidComparisons()
6971
array(10, '10', 3, '3', 'integer'),
7072
array(10, '10', 0, '0', 'integer'),
7173
array(42, '42', INF, 'INF', 'double'),
74+
array(4.15, '4.15', 0.1, '0.1', 'double'),
7275
array('22', '"22"', '10', '"10"', 'string'),
7376
);
7477
}

0 commit comments

Comments
 (0)
0