diff --git a/CHANGELOG.md b/CHANGELOG.md index d1365e4..840d75c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ## [Unreleased] +### Added + - Added MathUtils methods for converting to and from percentages + ## [10.2.0] - 2019-12-04 ### Added - Added shim methods for finding closest DateTimes from a sequence diff --git a/ICD.Common.Utils/MathUtils.cs b/ICD.Common.Utils/MathUtils.cs index 4143d68..ea48b0e 100644 --- a/ICD.Common.Utils/MathUtils.cs +++ b/ICD.Common.Utils/MathUtils.cs @@ -72,7 +72,7 @@ namespace ICD.Common.Utils public static double MapRange(double inputStart, double inputEnd, double outputStart, double outputEnd, double value) { if (inputStart.Equals(inputEnd)) - throw new DivideByZeroException(); + return outputStart; double slope = (outputEnd - outputStart) / (inputEnd - inputStart); return outputStart + slope * (value - inputStart); @@ -90,7 +90,7 @@ namespace ICD.Common.Utils public static decimal MapRange(decimal inputStart, decimal inputEnd, decimal outputStart, decimal outputEnd, decimal value) { if (inputStart.Equals(inputEnd)) - throw new DivideByZeroException(); + return outputStart; decimal slope = (outputEnd - outputStart) / (inputEnd - inputStart); return outputStart + slope * (value - inputStart); @@ -235,5 +235,29 @@ namespace ICD.Common.Utils long remainder = number % mod; return remainder < 0 ? remainder + mod : remainder; } + + /// + /// Converts the value to a percentage. + /// + /// + /// + /// + /// + public static float ToPercent(float min, float max, float value) + { + return MapRange(min, max, 0.0f, 1.0f, value); + } + + /// + /// Converts the value from a percentage. + /// + /// + /// + /// + /// + public static float FromPercent(float min, float max, float percent) + { + return MapRange(0.0f, 1.0f, min, max, percent); + } } }