Skip to content

Commit

Permalink
bug #28228 [Validator] Fix precision issue regarding floats and Divis…
Browse files Browse the repository at this point in the history
…ibleBy constraint (apfelbox)

This PR was merged into the 4.2-dev branch.

Discussion
----------

[Validator] Fix precision issue regarding floats and DivisibleBy constraint

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | -
| License       | MIT
| Doc PR        | -

Alternative to #28212

Commits
-------

ae04b48 [Validator] Fix precision issue regarding floats and DivisibleBy constraint
  • Loading branch information
nicolas-grekas committed Aug 21, 2018
2 parents 2df7320 + ae04b48 commit 6a4de22
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
Expand Up @@ -23,7 +23,17 @@ class DivisibleByValidator extends AbstractComparisonValidator
*/
protected function compareValues($value1, $value2)
{
return (float) 0 === fmod($value1, $value2);
if (!$value2 = abs($value2)) {
return false;
}
if (\is_int($value1 = abs($value1)) && \is_int($value2)) {
return 0 === ($value1 % $value2);
}
if (!$remainder = fmod($value1, $value2)) {
return true;
}

return sprintf('%.12e', $value2) === sprintf('%.12e', $remainder);
}

/**
Expand Down
Expand Up @@ -46,6 +46,8 @@ public function provideValidComparisons()
array(42, 21),
array(3.25, 0.25),
array('100', '10'),
array(4.1, 0.1),
array(-4.1, 0.1),
);
}

Expand All @@ -69,6 +71,7 @@ public function provideInvalidComparisons()
array(10, '10', 3, '3', 'integer'),
array(10, '10', 0, '0', 'integer'),
array(42, '42', INF, 'INF', 'double'),
array(4.15, '4.15', 0.1, '0.1', 'double'),
array('22', '"22"', '10', '"10"', 'string'),
);
}
Expand Down

0 comments on commit 6a4de22

Please sign in to comment.