/// <summary> /// Converts a unit value from the source terms to the target terms. /// </summary> /// <param name="val">Decimal value of the source terms</param> /// <param name="sourceSymbol">Unit symbol of the source value</param> /// <param name="targetSymbol">Unit symbol of the target value</param> /// <returns>Converted value</returns> public static decimal?Convert(decimal val, string sourceSymbol, string targetSymbol) { IEnumerable <SIUnits.Abstracts.BaseUnit> units = SIUnits.UnitManager.GetUnits(); SIUnits.Abstracts.BaseUnit source = units.FirstOrDefault(o => o.Symbol == sourceSymbol); SIUnits.Abstracts.BaseUnit target = units.FirstOrDefault(o => o.Symbol == targetSymbol); if (source == null) { throw new Exception("Couldn't determine appropriate source unit from '" + sourceSymbol + "'."); } else if (target == null) { throw new Exception("Couldn't determine appropriate target unit from '" + targetSymbol + "'."); } return(Convert(val, source, target)); }
/// <summary> /// Converts a unit value from the source terms to the target terms. /// </summary> /// <param name="val">Decimal value of the source terms</param> /// <param name="source">Unit of the source value</param> /// <param name="target">Unit of the target value</param> /// <returns></returns> public static decimal?Convert(decimal val, SIUnits.Abstracts.BaseUnit source, SIUnits.Abstracts.BaseUnit target) { decimal output = 0; if (source.Base == target.Base) { decimal baseValue = 0; string from = "", to = "", bas = ""; if (source != null) { if (source.GetType().IsAssignableFrom(typeof(FactoredUnit))) { baseValue = val / (source as FactoredUnit).Factor; bas = (source as FactoredUnit).DerivedFrom; from = source.Symbol; } else { baseValue = val; bas = source.Symbol; from = source.Symbol; } } else { throw new Exception("Source unit cannot be null."); } if (target != null) { if (target.GetType().IsAssignableFrom(typeof(FactoredUnit))) { if ((target as FactoredUnit).DerivedFrom == bas) { to = target.Symbol; output = baseValue * (target as FactoredUnit).Factor; } else { throw new Exception("Both units must come from the same derivation."); } } else { if (target.Symbol == bas) { to = target.Symbol; output = baseValue; } else { throw new Exception("Both units must come from the same derivation."); } } } else { throw new Exception("Target unit cannot be null."); } if (string.IsNullOrEmpty(from) || string.IsNullOrEmpty(to) || string.IsNullOrEmpty(bas)) { throw new Exception("Cannot convert items that are not derived from the same base unit."); } } else { throw new Exception("Source and Target units must be within the same unit class (ie. " + source.Base.ToString() + " or " + target.Base.ToString() + ")"); } return(output); }