From 66a56f956723f1c8a40dc3a2bdcbde52f1aad34d Mon Sep 17 00:00:00 2001 From: James Jackson-South Date: Tue, 4 Apr 2017 22:26:58 +1000 Subject: [PATCH] Add proper rounding compare --- .../TestUtilities/FloatRoundingComparer.cs | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 tests/ImageSharp.Tests/TestUtilities/FloatRoundingComparer.cs diff --git a/tests/ImageSharp.Tests/TestUtilities/FloatRoundingComparer.cs b/tests/ImageSharp.Tests/TestUtilities/FloatRoundingComparer.cs new file mode 100644 index 000000000..8bf5abbe1 --- /dev/null +++ b/tests/ImageSharp.Tests/TestUtilities/FloatRoundingComparer.cs @@ -0,0 +1,45 @@ +namespace ImageSharp.Tests.TestUtilities +{ + using System; + using System.Collections.Generic; + + /// + /// Allows the comparison of single-precision floating point values by precision. + /// + public struct FloatRoundingComparer : IEqualityComparer + { + /// + /// Initializes a new instance of the struct. + /// + /// The number of decimal places (valid values: 0-7) + public FloatRoundingComparer(int precision) + { + this.Precision = precision; + } + + /// + /// Gets the number of decimal places (valid values: 0-7) + /// + public int Precision { get; } + + /// + public bool Equals(float x, float y) + { + float xp = (float)Math.Round(x, this.Precision, MidpointRounding.AwayFromZero); + float yp = (float)Math.Round(y, this.Precision, MidpointRounding.AwayFromZero); + + return Comparer.Default.Compare(xp, yp) == 0; + } + + /// + public int GetHashCode(float obj) + { + unchecked + { + int hashCode = obj.GetHashCode(); + hashCode = (hashCode * 397) ^ this.Precision.GetHashCode(); + return hashCode; + } + } + } +} \ No newline at end of file