8000 [Validator] Improve DivisibleBy validator by apfelbox · Pull Request #28212 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Validator] Improve DivisibleBy validator #28212

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix several issues regarding floats and DivisibleBy validator
  • Loading branch information
Jannik Zschiesche committed Aug 16, 2018
commit 7ad04145dab7e24648399a07283d32ab38137c68
6C9C
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,29 @@ class DivisibleByValidator extends AbstractComparisonValidator
*/
protected function compareValues($value1, $value2)
{
return (float) 0 === fmod($value1, $value2);
$value1 = \abs($value1);
$value2 = \abs($value2);
$epsilon = 0.0000001;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about making this configurable?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I‘m not sure whether this would actually add anything.

Might make sense to add something like FloatUtils to capsiluate some of this logic (comparing floats etc)


// can't divide by 0
if ($value2 < $epsilon)
{
return false;
}

// 0 is divisible by everything
if ($value1 < $epsilon)
{
return true;
}

// if the divisor is larger than the dividend, it will never cleanly divide
if ($value2 > $value1)
{
return false;
}

return \abs($value1 - round($value1 / $value2) * $value2) < $epsilon;
}

/**
Expand Down
0