/// <summary> /// Converts this quantity from this <see cref="Unit"/> to another <see cref="MeasureUnit"/>. /// Must be called only if <see cref="CanConvertTo(MeasureUnit)"/> returned true otherwise an <see cref="ArgumentException"/> /// is thrown. /// </summary> /// <param name="u">The target unit of measure.</param> /// <returns>The quantity exporessed with the target unit.</returns> public Quantity ConvertTo(MeasureUnit u) { if (Unit == u) { return(this); } if (!CanConvertTo(u)) { if (u.Context != Unit.Context) { throw new ArgumentException($"Can not convert between units in different contexts ('{Unit}' to '{u}')."); } throw new ArgumentException($"Can not convert from '{Unit}' to '{u}'."); } if (Unit.Normalization == u.Normalization) { FullFactor ratio = Unit.NormalizationFactor.DivideBy(u.NormalizationFactor); return(new Quantity(Value * ratio.ToDouble(), u)); } else { FullFactor ratio = Unit.NormalizationFactor.Multiply(u.NormalizationFactor); return(new Quantity(1 / (Value * ratio.ToDouble()), u)); } }
/// <summary> /// Compares this quantity to another one. /// </summary> /// <param name="other">The other quantity to compare.</param> /// <returns></returns> public int CompareTo(Quantity other) { var tU = Unit; var oU = other.Unit; // Do the 2 units belong to the same (possibly null) context? if (tU.Context == oU.Context) { // First chexk our equality: we must do this first to ensure coherency. if (ToNormalizedString() == other.ToNormalizedString()) { return(0); } // Same unit, we compare the Values. if (tU == oU) { return(Value.CompareTo(other.Value)); } // Same normalized units, we convert this Value to the other unit before comparison. if (tU.Normalization == oU.Normalization) { FullFactor ratio = tU.NormalizationFactor.DivideBy(oU.NormalizationFactor); return((Value * ratio.ToDouble()).CompareTo(other.Value)); } // Inverted normalized units, we convert this Value to the other unit before comparison. if (tU.Normalization == oU.Normalization.Invert()) { FullFactor ratio = tU.NormalizationFactor.Multiply(oU.NormalizationFactor); return((1 / (Value * ratio.ToDouble())).CompareTo(other.Value)); } // No possible conversion. How to compare kilograms and milliSievert? // Using their abbreviation (here kilogram will be "smaller" than milliSievert) return(tU.Abbreviation.CompareTo(oU.Abbreviation)); } // Not in the same context. if (tU == MeasureUnit.None) { return(-1); } if (oU == MeasureUnit.None) { return(1); } return(tU.Context.Name.CompareTo(oU.Context.Name)); }