From 65124e840368b0c1bc56e1924f384936713efd66 Mon Sep 17 00:00:00 2001 From: Jon Sagara Date: Wed, 19 Jul 2023 19:14:16 -0700 Subject: [PATCH] Fixed lb to kg / kg to lb conversion error. --- IdParser.Test/WeightTests.cs | 30 ++++++++++++++++++++++++++++++ IdParser/Weight.cs | 17 ++++++++++++++--- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/IdParser.Test/WeightTests.cs b/IdParser.Test/WeightTests.cs index 8c0e85d..9ed8087 100644 --- a/IdParser.Test/WeightTests.cs +++ b/IdParser.Test/WeightTests.cs @@ -62,5 +62,35 @@ public void MetricDisplayTest() Assert.AreEqual("33 kg", actual); } + + [TestMethod] + public void PoundsToKilogramsTest() + { + var weight = Weight.FromImperial(175); + var expectedKg = 79.4; + + Assert.IsTrue(weight.Kilograms.Value.Equals1DigitPrecision(expectedKg)); + } + + [TestMethod] + public void PoundsTest() + { + // This is internally converted to kg. Ensure it is round-tripped back to the expected value. + var weight = Weight.FromImperial(175); + var expected = "175 lbs"; + + Assert.AreEqual(expected, weight.ToString()); ; + } + } + + internal static class DoubleExtensions + { + private const double _1Digit = 0.1; + + internal static bool Equals1DigitPrecision(this double value, double comparison) + { + var difference = Math.Abs(value - comparison); + return difference < _1Digit; + } } } diff --git a/IdParser/Weight.cs b/IdParser/Weight.cs index c55d02e..3ce4f97 100644 --- a/IdParser/Weight.cs +++ b/IdParser/Weight.cs @@ -11,6 +11,17 @@ public class Weight : IComparable, IEquatable { private const double PoundsPerKilogram = 2.20462262; + private static double PoundsToKilograms(int pounds) + { + return pounds / PoundsPerKilogram; + } + + private static int KilogramsToPounds(double kilograms) + { + return (int)Math.Round(kilograms * PoundsPerKilogram, 0); + } + + // In order for JSON serialization and deserialization to work in both Json.NET // and ServiceStack.Text, an immutable type has to: // - Be a class and not a struct (immutable structs do not deserialize in ServiceStack) @@ -34,7 +45,7 @@ public static Weight FromMetric(double kilograms) public static Weight FromImperial(int pounds) { - return new Weight(null, pounds * PoundsPerKilogram, false); + return new Weight(null, PoundsToKilograms(pounds), false); } public static Weight FromRange(WeightRange weightRange) @@ -44,7 +55,7 @@ public static Weight FromRange(WeightRange weightRange) internal void SetImperial(int pounds) { - Kilograms = pounds * PoundsPerKilogram; + Kilograms = PoundsToKilograms(pounds); IsMetric = false; } @@ -71,7 +82,7 @@ public override string ToString() return $"{Kilograms} kg"; } - return $"{(int)(Kilograms.Value / PoundsPerKilogram)} lbs"; + return $"{KilogramsToPounds(Kilograms.Value)} lbs"; } #region IComparable