Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
30 changes: 30 additions & 0 deletions IdParser.Test/WeightTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
}
17 changes: 14 additions & 3 deletions IdParser/Weight.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,17 @@ public class Weight : IComparable<Weight>, IEquatable<Weight>
{
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)
Expand All @@ -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)
Expand All @@ -44,7 +55,7 @@ public static Weight FromRange(WeightRange weightRange)

internal void SetImperial(int pounds)
{
Kilograms = pounds * PoundsPerKilogram;
Kilograms = PoundsToKilograms(pounds);
IsMetric = false;
}

Expand All @@ -71,7 +82,7 @@ public override string ToString()
return $"{Kilograms} kg";
}

return $"{(int)(Kilograms.Value / PoundsPerKilogram)} lbs";
return $"{KilogramsToPounds(Kilograms.Value)} lbs";
}

#region IComparable
Expand Down