using LoreSoft.MathExpressions.Metadata; namespace LoreSoft.MathExpressions.UnitConversion { /// Units for Mass public enum MassUnit { /// Milligram unit (mg) [Abbreviation("mg")] Milligram = 0, /// Gram unit (g) [Abbreviation("g")] Gram = 1, /// Kilogram unit (kg) [Abbreviation("kg")] Kilogram = 2, /// Ounce unit (oz) [Abbreviation("oz")] Ounce = 3, /// Pound unit (lb) [Abbreviation("lb")] Pound = 4, /// Ton unit (ton) [Abbreviation("ton")] Ton = 5, } /// /// Class representing mass convertion. /// public static class MassConverter { // In enum order private static readonly double[] factors = new double[] { 0.000001d, //milligram 0.001d, //gram 1d, //kilogram 0.45359237d/16d, //ounce 0.45359237d, //pound 0.45359237d*2000d, //ton [short, US] }; /// /// Converts the specified from unit to the specified unit. /// /// Covert from unit. /// Covert to unit. /// Covert from value. /// The converted value. public static double Convert( MassUnit fromUnit, MassUnit toUnit, double fromValue) { if (fromUnit == toUnit) return fromValue; double fromFactor = factors[(int)fromUnit]; double toFactor = factors[(int)toUnit]; double result = fromFactor * fromValue / toFactor; return result; } } }