public static string FormatCompound <T>(this T q, ICollection <Unit <T> > units, string separator = " ", CompoundZeroHandling zeroHandling = CompoundZeroHandling.RemoveAny, string lastNumberFormat = null, bool longNames = false, bool discardLastFraction = false) where T : unmanaged, IQuantity <T> { // compose info array var infolist = new List <CompoundFormatInfo <T> .Info>(); foreach (var unit in units) { infolist.Add(new CompoundFormatInfo <T> .Info(unit)); } var formatInfo = new CompoundFormatInfo <T>(separator, lastNumberFormat, zeroHandling, longNames, discardLastFraction, infolist.ToArray()); return(q.FormatCompound(formatInfo)); }
public static string FormatCompound <T>(this T q, CompoundFormatInfo <T> formatInfo) where T : unmanaged, IQuantity <T> { var str = new StringBuilder(); T remainder = q; if (remainder.BaseValue < 0) { remainder = remainder.Multiply(-1); str.Append("-"); } bool writtenAnything = false; for (int i = 0; i < formatInfo.UnitCount; i++) { var unit = formatInfo.GetUnit(i); var zeroHandling = formatInfo.GetZeroHandling(i); bool isLast = i == formatInfo.UnitCount - 1; double val = unit.ConvertTo(remainder); double whole = Math.Floor(val); double frac = val - whole; if (!isLast) { bool isZero = whole == 0.0; bool take = true; if (zeroHandling == CompoundZeroHandling.RemoveAny && isZero) { take = false; } else if (zeroHandling == CompoundZeroHandling.TrimBeginning && isZero && !writtenAnything) { take = false; } if (take) { var wholeQ = unit.ConvertFrom(whole); str.Append(wholeQ.FormatAs(unit, formatInfo.GetNumberFormat(i), formatInfo.UseLongNames, formatInfo.GetUnitName(i))); str.Append(formatInfo.GetSeparator(i)); writtenAnything = true; } remainder = unit.ConvertFrom(frac); } else { if (formatInfo.DiscardLastFraction) { remainder = unit.ConvertFrom(whole); } string last = remainder.FormatAs(unit, formatInfo.LastNumberFormat, formatInfo.UseLongNames, formatInfo.GetUnitName(i)); if (zeroHandling != CompoundZeroHandling.RemoveAny || last.IndexOfAny( new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' }) >= 0) { str.Append(last); writtenAnything = true; } } } return(str.ToString()); }