Exemplo n.º 1
0
 public UnitPoint2D(SIPrefix prefix, IUnitDefinition unit, double x, double y)
     : base(
         prefix.GetMultiplier() * unit.ConvertToUnitValue(x).Value,
         prefix.GetMultiplier() * unit.ConvertToUnitValue(y).Value)
 {
     Unit = unit.CorrespondingCompoundUnit;
 }
Exemplo n.º 2
0
        /// <summary>
        /// Format a numeric value using SI prefexes.
        ///
        /// eg: 13401 -> 13.4 k
        ///
        /// </summary>
        /// <param name="value">value to format</param>
        /// <param name="unit">unit string</param>
        /// <param name="exponent">Exponennt to the existing value. eg: if value was km rather than m this would be 3.</param>
        /// <param name="sigFigs">number of signifigant figures to display</param>
        /// <returns></returns>
        public static string ToStringSI(this float value, int sigFigs = 3, int exponent = 0, string unit = null)
        {
            EMRUtils.Log("Getting prefix for exponent of " + exponent);
            SIPrefix prefix = value.GetSIPrefix(exponent);

            EMRUtils.Log("Found prefix of " + prefix);
            return(prefix.FormatSI(value, sigFigs, exponent, unit));
        }
Exemplo n.º 3
0
 /// <summary>
 /// 指定のPrefixで丸める
 /// </summary>
 /// <param name="value">対象の値</param>
 /// <param name="prefix">Prefix値で丸められる</param>
 public static float Convert(float value, SIPrefix prefix)
 {
     for (int i = 0; i < (int)prefix; i++)
     {
         value /= 1024;
     }
     return(value);
 }
Exemplo n.º 4
0
        public static Vector2D In(this UnitVector2D unitPoint, SIPrefix targetSIPrefix, IUnitDefinition targetUnit)
        {
            var multiplier = new UnitValue(unitPoint.Unit, 1).In(targetSIPrefix, targetUnit);

            return(new Vector2D(
                       multiplier * unitPoint.X,
                       multiplier * unitPoint.Y));
        }
Exemplo n.º 5
0
 public static string StringRepresentation(this SIPrefix prefix)
 {
     if (!SIPrefixStringRepresentation.ContainsKey(prefix))
     {
         throw new ArgumentOutOfRangeException(nameof(prefix), prefix, null);
     }
     return(SIPrefixStringRepresentation[prefix]);
 }
Exemplo n.º 6
0
        public static double GetMultiplier(this SIPrefix prefix)
        {
            switch (prefix)
            {
            case SIPrefix.Femto:
                return(1e-15);

            case SIPrefix.Pico:
                return(1e-12);

            case SIPrefix.Nano:
                return(1e-9);

            case SIPrefix.Micro:
                return(1e-6);

            case SIPrefix.Milli:
                return(1e-3);

            case SIPrefix.Centi:
                return(1e-2);

            case SIPrefix.Deci:
                return(1e-1);

            case SIPrefix.None:
                return(1);

            case SIPrefix.Deca:
                return(1e1);

            case SIPrefix.Hecto:
                return(1e2);

            case SIPrefix.Kilo:
                return(1e3);

            case SIPrefix.Mega:
                return(1e6);

            case SIPrefix.Giga:
                return(1e9);

            case SIPrefix.Tera:
                return(1e12);

            case SIPrefix.Peta:
                return(1e15);

            case SIPrefix.Exa:
                return(1e18);

            default:
                throw new ArgumentOutOfRangeException(nameof(prefix), prefix, null);
            }
        }
        public void CalculateMass()
        {
            if (tankList == null || !massDirty)
            {
                return;
            }
            massDirty = false;

            double basemass = basemassConst + basemassPV * volume;

            if (basemass >= 0)
            {
                double tankDryMass = tankList
                                     .Where(fuel => fuel.maxAmount > 0 && fuel.utilization > 0)
                                     .Sum(fuel => (float)fuel.maxAmount * fuel.mass / fuel.utilization);

                mass = (float)(basemass + tankDryMass) * MassMult;

                if (part.mass != mass)
                {
                    part.mass = mass;
                    MassChanged(mass);
                    // compute massDelta based on prefab, if available.
                    if ((object)(part.partInfo) != null)
                    {
                        if ((object)(part.partInfo.partPrefab) != null)
                        {
                            massDelta = part.mass - part.partInfo.partPrefab.mass;
                        }
                    }
                }
            }
            else
            {
                mass = part.mass;                 // display dry mass even in this case.
            }

            if (isEditor)
            {
                UsedVolume = tankList
                             .Where(fuel => fuel.maxAmount > 0 && fuel.utilization > 0)
                             .Sum(fuel => fuel.maxAmount / fuel.utilization);

                SIPrefix pfx = volume.GetSIPrefix();
                Func <double, string> formatter = pfx.GetFormatter(volume);
                volumeDisplay = "Avail: " + formatter(AvailableVolume) + pfx.PrefixString() + MFSSettings.unitLabel + " / Tot: " + formatter(volume) + pfx.PrefixString() + MFSSettings.unitLabel;

                double resourceMass = part.Resources.Cast <PartResource> ().Sum(r => r.maxAmount * r.info.density);

                double wetMass = mass + resourceMass;
                massDisplay = "Dry: " + FormatMass(mass) + " / Wet: " + FormatMass((float)wetMass);

                UpdateTweakableMenu();
            }
        }
Exemplo n.º 8
0
        public static string KiloFormat(double input, int digit)
        {
            if (input < 1000)
            {
                //var format = string.Format("N{0}",digit.ToString());
                return(DecimalFormat((decimal)input));
            }
            var number = SIPrefix.GetInfo((long)input, digit);

            return(number.AmountWithPrefix);
        }
Exemplo n.º 9
0
 public static SIPrefix PrefixFromExponent(int exponent, SIPrefix minimumPrefix, SIPrefix maximumPrefix)
 {
     if (exponent < (int)minimumPrefix)
     {
         return(minimumPrefix);
     }
     if (exponent > (int)maximumPrefix)
     {
         return(maximumPrefix);
     }
     return((SIPrefix)(exponent - exponent % 3));
 }
Exemplo n.º 10
0
        private bool UpdateResources()
        {
            // Hopefully we can just fiddle with the existing part resources.
            // This saves having to make the window dirty, which breaks dragging on sliders.
            if (part.Resources.Count != selectedTankType.resources.Count)
            {
                Debug.LogWarning("*TCS* Selected and existing resource counts differ");
                return(false);
            }

            for (int i = 0; i < part.Resources.Count; ++i)
            {
                PartResource partRes = part.Resources[i];
                TankResource tankRes = selectedTankType.resources[i];

                if (partRes.resourceName != tankRes.name)
                {
                    Debug.LogWarning("*TCS* Selected and existing resource names differ");
                    return(false);
                }

                //double maxAmount = (float)Math.Round(tankRes.unitsConst + tankVolume * tankRes.unitsPerKL + mass * tankRes.unitsPerT, 2);
                double maxAmount = CalculateMaxResourceAmount(tankRes);

                // ReSharper disable CompareOfFloatsByEqualityOperator
                if (partRes.maxAmount == maxAmount)
                {
                    continue;
                }

                if (tankRes.forceEmpty)
                {
                    partRes.amount = 0;
                }
                else if (partRes.maxAmount == 0)
                {
                    partRes.amount = maxAmount;
                }
                else
                {
                    SIPrefix pfx = maxAmount.GetSIPrefix();
                    partRes.amount = pfx.Round(partRes.amount * maxAmount / partRes.maxAmount, 4);
                }
                partRes.maxAmount = maxAmount;
                // ReSharper restore CompareOfFloatsByEqualityOperator

                MaxAmountChanged(part, partRes, partRes.maxAmount);
                InitialAmountChanged(part, partRes, partRes.amount);
            }

            return(true);
        }
        public override void UpdateItem()
        {
            base.UpdateItem();

            SIPrefix prefix = (resource.maxAmount).GetSIPrefix();
            // ReSharper disable once InconsistentNaming
            Func <double, string> Formatter = prefix.GetFormatter(resource.maxAmount, sigFigs: 4);

            resourceMax.Text  = Formatter(resource.maxAmount) + " " + prefix.PrefixString();
            resourceAmnt.Text = Formatter(resource.amount);

            oldSliderValue = slider.Value = (float)(resource.amount / resource.maxAmount);
        }
Exemplo n.º 12
0
        /// <summary>
        /// 適切なPrefixで丸める
        /// </summary>
        /// <param name="value">対象の値</param>
        /// <param name="prefix">使用されたPrefix値</param>
        private static float AutoOptimizePrefix(float value, out SIPrefix prefix)
        {
            int iprefix;

            for (iprefix = 0; iprefix < 2; iprefix++)
            {
                if (value < 1024)
                {
                    break;
                }
                value /= 1024;
            }
            prefix = (SIPrefix)iprefix;
            return(value);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Get a formatter function. This is useful when you have a range of values you'd like formatted the same way.
        /// </summary>
        public static Func <double, string> GetFormatter(this SIPrefix pfx, double value, int sigFigs = 3, int exponent = 0)
        {
            int    exp = (int)(Math.Floor(Math.Log10(Math.Abs(value)))) - (int)pfx + exponent;
            double div = Math.Pow(10, (int)pfx - exponent);

            if (exp < 0)
            {
                return(v => (v / div).ToString("F" + (sigFigs - 1)));
            }
            if (exp >= sigFigs)
            {
                double mult = Math.Pow(10, exp - sigFigs + 1);
                return(v => (Math.Round(v / div / mult) * mult).ToString("F0"));
            }
            return(v => (v / div).ToString("F" + (sigFigs - exp - 1)));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Tries to get a prefixed unit from a shortcut, considering all units in this environment.
        /// </summary>
        /// <param name="shortCut">The shortcut. Can be a compound of prefix and unit, e.g. 'mA'. An empty string is converted to <see cref="Altaxo.Units.Dimensionless.Unity.Instance"/></param>
        /// <param name="result">If successfully, the resulting prefixed unit.</param>
        /// <returns>True if the conversion was successful; false otherwise.</returns>
        /// <exception cref="ArgumentNullException">s</exception>
        public bool TryGetPrefixedUnitFromShortcut(string shortCut, out IPrefixedUnit result)
        {
            if (null == shortCut)
            {
                throw new ArgumentNullException(nameof(shortCut));
            }

            shortCut = shortCut.Trim();

            if ("" == shortCut) // If string is empty, we consider this as a dimensionless unit "Unity"
            {
                result = new PrefixedUnit(SIPrefix.None, Altaxo.Units.Dimensionless.Unity.Instance);
                return(true);
            }

            SIPrefix prefix = null;

            foreach (IUnit u in UnitsSortedByShortcutLengthDescending) // for each unit
            {
                if (string.IsNullOrEmpty(u.ShortCut) || (!shortCut.EndsWith(u.ShortCut)))
                {
                    continue;
                }

                var prefixString = shortCut.Substring(0, shortCut.Length - u.ShortCut.Length);

                if (prefixString.Length == 0) // if prefixString is empty, then it is the unit without prefix
                {
                    result = new PrefixedUnit(SIPrefix.None, u);
                    return(true);
                }

                prefix = SIPrefix.TryGetPrefixFromShortcut(prefixString);

                if (null != prefix) // we found a prefix, thus we can return prefix + unit
                {
                    result = new PrefixedUnit(prefix, u);
                    return(true);
                }
            }

            result = null;
            return(false);
        }
        private void OnSliderChanged(IUIObject obj)
        {
            // ReSharper disable once CompareOfFloatsByEqualityOperator
            if (oldSliderValue == slider.Value)
            {
                return;
            }
            oldSliderValue = slider.Value;

            SIPrefix prefix = resource.maxAmount.GetSIPrefix();

            resource.amount = prefix.Round(slider.Value * resource.maxAmount, digits: 4);
            PartMessageService.Send <PartResourceInitialAmountChanged>(this, part, resource, resource.amount);
            if (scene == UI_Scene.Editor)
            {
                SetSymCounterpartsAmount(resource.amount);
            }
            resourceAmnt.Text = resource.amount.ToString("F1");
            GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship);
        }
Exemplo n.º 16
0
        /// <summary>
        /// The prefix string for a particular exponent. Note Micro will use the string "mic" rather than "µ", so is longer.
        /// </summary>
        public static string PrefixString(this SIPrefix pfx)
        {
            switch (pfx)
            {
            case SIPrefix.None: return("");

            case SIPrefix.Kilo: return("k");

            case SIPrefix.Mega: return("M");

            case SIPrefix.Giga: return("G");

            case SIPrefix.Tera: return("T");

            case SIPrefix.Peta: return("P");

            case SIPrefix.Exa: return("E");

            case SIPrefix.Zotta: return("Z");

            case SIPrefix.Yotta: return("Y");

            case SIPrefix.Milli: return("m");

            case SIPrefix.Micro: return("u");

            case SIPrefix.Nano: return("n");

            case SIPrefix.Pico: return("p");

            case SIPrefix.Femto: return("f");

            case SIPrefix.Atto: return("a");

            case SIPrefix.Zepto: return("z");

            case SIPrefix.Yocto: return("y");

            default: throw new ArgumentException("Illegal prefix", "pfx");
            }
        }
Exemplo n.º 17
0
 public static SIPrefix GetSIPrefix(Unit unit, double value, SIPrefix minimumPrefix, SIPrefix maximumPrefix, SIPrefix defaultPrefix, int signiFicantDigits = 15)
 {
     if (unit == Unit.DegreeAngle || unit == Unit.Percent || unit == Unit.None)
     {
         return(SIPrefix.None);
     }
     if (Math.Abs(value) > Double.Epsilon)
     {
         value = Math.Abs(value);
         var    prefixBase            = 3 * unit.PrefixExponent;
         double significantDigitsBias = 1;
         if (signiFicantDigits < Math.Abs(3 * unit.PrefixExponent))
         {
             significantDigitsBias = Math.Pow(10, Math.Abs(3 * unit.PrefixExponent - signiFicantDigits));
         }
         var exponent = (int)Math.Floor((Math.Log10(value * significantDigitsBias)) / prefixBase) * prefixBase;
         return(PrefixFromExponent(exponent / unit.PrefixExponent, minimumPrefix, maximumPrefix));
     }
     //use the more suitable prefix from limits for value == 0.0
     return((SIPrefix)Math.Max((int)minimumPrefix, Math.Min((int)defaultPrefix, (int)maximumPrefix)));
 }
Exemplo n.º 18
0
 public static UnitValue To(this int value, SIPrefix prefix, IUnitDefinition unit)
 {
     return(To((double)value, prefix, unit));
 }
Exemplo n.º 19
0
        public void SelectSIPrefixAsExpected(double value, SIPrefix expected)
        {
            var actual = value.SelectSIPrefix();

            Assert.That(actual, Is.EqualTo(expected));
        }
Exemplo n.º 20
0
 public static UnitVector2D To(this Vector2D point, SIPrefix siPrefix, IUnitDefinition unit)
 {
     return(new UnitVector2D(siPrefix, unit, point.X, point.Y));
 }
Exemplo n.º 21
0
 public static SIPrefix PrefixFromExponent(int exponent, SIPrefix minimumPrefix, SIPrefix maximumPrefix)
 {
     if (exponent < (int)minimumPrefix)
     {
         return minimumPrefix;
     }
     if (exponent > (int)maximumPrefix)
     {
         return maximumPrefix;
     }
     return (SIPrefix)(exponent - exponent % 3);
 }
Exemplo n.º 22
0
 internal static string FormatSI(this SIPrefix pfx, double value, int sigFigs = 3, int exponent = 0, string unit = null)
 {
     return(string.Format("{0}{1}{2}", pfx.GetFormatter(value, sigFigs, exponent)(value), pfx.PrefixString(), unit));
 }
Exemplo n.º 23
0
        public static UnitValue To(this double value, SIPrefix prefix, CompoundUnit unit)
        {
            var multiplier = GetMultiplier(prefix);

            return(new UnitValue(unit, multiplier * value));
        }
Exemplo n.º 24
0
        public static UnitValue To(this double value, SIPrefix prefix, IUnitDefinition unit)
        {
            var multiplier = GetMultiplier(prefix);

            return(unit.ConvertToUnitValue(multiplier * value));
        }
Exemplo n.º 25
0
 public SIUnit(string name, string shortcut, SIPrefix prefix = null)
     : base(name, shortcut)
 {
     Prefix = prefix;
 }
Exemplo n.º 26
0
        /// <summary>
        /// Round a value with respect the the given SI prefix.
        ///
        /// eg:
        /// SIPrefix.Mega.Round(34.456e6f, digits:1) -> 34.6e6f
        ///
        /// </summary>
        /// <param name="pfx">The SI prefix</param>
        /// <param name="value">Value to round</param>
        /// <param name="digits">Number of decimal places. Negatives will work (eg: -1 rounds to nearest 10)</param>
        /// <param name="exponent">Natural exponent of value, eg: use 3 if value is km rather than m</param>
        /// <returns></returns>
        public static float Round(this SIPrefix pfx, float value, int digits = 3, int exponent = 0)
        {
            float div = Mathf.Pow(10, (int)pfx - digits + exponent);

            return(Mathf.Round(value / div) * div);
        }
Exemplo n.º 27
0
        private static void ParseSimpleUnit(string unitString, out IUnitDefinition unit, out SIPrefix siPrefix)
        {
            if (string.IsNullOrEmpty(unitString))
            {
                throw new FormatException($"Invalid unit '{unitString}'");
            }

            var normalizedUnitString = unitString.Trim();

            if (Unit.Effective.InverseStringRepresentationLookup.ContainsKey(unitString))
            {
                siPrefix = SIPrefix.None;
                unit     = Unit.Effective.InverseStringRepresentationLookup[unitString];
                return;
            }
            if (normalizedUnitString.Length == 1)
            {
                throw new FormatException($"Invalid unit '{unitString}'");
            }

            // Try with SI multiplier prefix
            var prefixString  = unitString.Substring(0, 1);
            var newUnitString = unitString.Substring(1);

            if (!Unit.Effective.InverseStringRepresentationLookup.ContainsKey(newUnitString))
            {
                throw new FormatException($"Invalid unit '{unitString}'");
            }
            unit = Unit.Effective.InverseStringRepresentationLookup[newUnitString];
            if (UnitValueExtensions.InverseSIPrefixStringRepresentation.ContainsKey(prefixString))
            {
                siPrefix = UnitValueExtensions.InverseSIPrefixStringRepresentation[prefixString];
                return;
            }
            throw new FormatException($"Invalid unit '{unitString}'");
        }
Exemplo n.º 28
0
        /// <summary>
        /// Round a value with respect the the given SI prefix.
        ///
        /// eg:
        /// SIPrefix.Mega.Round(34.456e6, digits:1) -> 34.6e6
        ///
        /// </summary>
        /// <param name="pfx">The SI prefix</param>
        /// <param name="value">Value to round</param>
        /// <param name="digits">Number of decimal places. Negatives will work (eg: -1 rounds to nearest 10)</param>
        /// <param name="exponent">Natural exponent of value, eg: use 3 if value is km rather than m</param>
        /// <returns></returns>
        public static double Round(this SIPrefix pfx, double value, int digits = 3, int exponent = 0)
        {
            double div = Math.Pow(10, (int)pfx - digits + exponent);

            return(Math.Round(value / div) * div);
        }
Exemplo n.º 29
0
 public static UnitPoint3D To(this Point3D point, SIPrefix siPrefix, IUnitDefinition unit)
 {
     return(new UnitPoint3D(siPrefix, unit, point.X, point.Y, point.Z));
 }
Exemplo n.º 30
0
        /// <summary>
        /// Format a numeric value using SI prefexes.
        ///
        /// eg: 13401 -> 13.4 k
        ///
        /// </summary>
        /// <param name="value">value to format</param>
        /// <param name="unit">unit string</param>
        /// <param name="exponent">Exponennt to the existing value. eg: if value was km rather than m this would be 3.</param>
        /// <param name="sigFigs">number of signifigant figures to display</param>
        /// <returns></returns>
        public static string ToStringSI(this float value, int sigFigs = 3, int exponent = 0, string unit = null)
        {
            SIPrefix prefix = value.GetSIPrefix(exponent);

            return(prefix.FormatSI(value, sigFigs, exponent, unit));
        }
Exemplo n.º 31
0
    // FormatCash
//	public static string FormatCash(ulong num)
//	{
//		if (Language.CurrentLanguage () != LanguageCode.KO) {
//			return SIPrefix.GetInfo (num, 0).AmountWithPrefix;
//		}
//
//		bool UseDecimal=false;
//		string Sign ="";
//		int i =0;
//		int Level =0;
//
//		string[] NumberChar = new string[]{ "", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
//		string[] LevelChar = new string[]{ "", "십", "백", "천" };
//		string[] DecimalChar = new string[]{ "", "만", "억", "조", "경", "해", "자" };
//
//		string strValue = string.Format("{0}", num);
//		string NumToKorea = Sign;
//		UseDecimal = false;
//
//		for( i = 0 ; i<strValue.Length; i++)
//		{
//			Level = strValue.Length - i;
//
//			if (strValue.Substring (i, 1) != "0") {
//				UseDecimal = true;
//				if (((Level - 1) % 4) == 0) {
//					NumToKorea = NumToKorea + NumberChar [int.Parse (strValue.Substring (i, 1))] + DecimalChar [(Level - 1) / 4];
//					UseDecimal = false;
//				} else {
//					if (strValue.Substring (i, 1) == "1")
//						NumToKorea = NumToKorea + LevelChar [(Level - 1) % 4];
//					else
//						NumToKorea = NumToKorea + NumberChar [int.Parse (strValue.Substring (i, 1))] + LevelChar [(Level - 1) % 4];
//				}
//			} else {
//				if (((Level - 1) % 4) == 0 && strValue.Length <= 8) {
//					NumToKorea = NumToKorea + DecimalChar [(Level - 1) / 4];
//				}
//			}
//		}
//		return NumToKorea;
//	}

    // FormatCash
    public static string FormatCash(double num)
    {
        return(SIPrefix.GetInfo(num, 2).AmountWithPrefix);
    }
Exemplo n.º 32
0
        private ValidationResult ConvertValidate(string s, out DimensionfulQuantity result)
        {
            if (null != _lastConvertedQuantity && s == _lastConvertedString)
            {
                result = (DimensionfulQuantity)_lastConvertedQuantity;
                return(ValidateSuccessfullyConvertedQuantity(result));
            }

            result = new DimensionfulQuantity();
            double   parsedValue;
            SIPrefix prefix = null;

            s = s.Trim();

            if (_allowNaN && null != _representationOfNaN && s.Trim() == _representationOfNaN.Trim())
            {
                result = new DimensionfulQuantity(double.NaN, SIPrefix.None, _lastConvertedQuantity.HasValue ? _lastConvertedQuantity.Value.Unit : _unitEnvironment.DefaultUnit.Unit);
                return(ValidateSuccessfullyConvertedQuantity(result));
            }

            if (string.IsNullOrEmpty(s))
            {
                return(new ValidationResult(false, "The text box is empty. You have to enter a valid numeric quantity"));
            }

            foreach (IUnit u in _unitEnvironment.UnitsSortedByShortcutLengthDescending)
            {
                if (string.IsNullOrEmpty(u.ShortCut) || (!s.EndsWith(u.ShortCut)))
                {
                    continue;
                }

                s = s.Substring(0, s.Length - u.ShortCut.Length);

                if (!u.Prefixes.ContainsNonePrefixOnly && s.Length > 0)
                {
                    // try first prefixes of bigger length, then of smaller length
                    for (int pl = SIPrefix.MaxShortCutLength; pl > 0; --pl)
                    {
                        if (s.Length < pl)
                        {
                            continue;
                        }
                        prefix = SIPrefix.TryGetPrefixFromShortcut(s.Substring(s.Length - pl));
                        if (null != prefix)
                        {
                            s = s.Substring(0, s.Length - prefix.ShortCut.Length);
                            break;
                        }
                    }
                }

                if (double.TryParse(s, System.Globalization.NumberStyles.Float, _conversionCulture, out parsedValue))
                {
                    result = new DimensionfulQuantity(parsedValue, prefix, u);
                    return(ValidateSuccessfullyConvertedQuantity(result));
                }
                else
                {
                    string firstPart;
                    if (null != prefix)
                    {
                        firstPart = string.Format("The last part \"{0}\" of your entered text is recognized as prefixed unit, ", prefix.ShortCut + u.ShortCut);
                    }
                    else
                    {
                        firstPart = string.Format("The last part \"{0}\" of your entered text is recognized as unit, ", u.ShortCut);
                    }

                    string lastPart;
                    if (string.IsNullOrEmpty(s.Trim()))
                    {
                        lastPart = string.Format("but the first part is empty. You have to prepend a numeric value!");
                    }
                    else
                    {
                        lastPart = string.Format("but the first part \"{0}\" is not recognized as a numeric value!", s);
                    }

                    return(new ValidationResult(false, firstPart + lastPart));
                }
            }

            // if nothing is found in this way, we try to split the text
            var parts = s.Split(new char[] { ' ', '\t' }, 2, StringSplitOptions.RemoveEmptyEntries);

            // try to parse the first part as a number
            if (!double.TryParse(parts[0], System.Globalization.NumberStyles.Float, _conversionCulture, out parsedValue))
            {
                return(new ValidationResult(false, string.Format("The part \"{0}\" of your entered text was not recognized as a numeric value.", parts[0])));
            }

            string unitString = parts.Length >= 2 ? parts[1] : string.Empty;

            if (string.IsNullOrEmpty(unitString))
            {
                if (null != _lastConvertedQuantity)
                {
                    result = new DimensionfulQuantity(parsedValue, ((DimensionfulQuantity)_lastConvertedQuantity).Prefix, ((DimensionfulQuantity)_lastConvertedQuantity).Unit);
                    return(ValidateSuccessfullyConvertedQuantity(result));
                }
                else if (null != _unitEnvironment && null != _unitEnvironment.DefaultUnit)
                {
                    result = new DimensionfulQuantity(parsedValue, _unitEnvironment.DefaultUnit.Prefix, _unitEnvironment.DefaultUnit.Unit);
                    return(ValidateSuccessfullyConvertedQuantity(result));
                }
                else
                {
                    return(new ValidationResult(false, "No unit was given by you and no default unit could be deduced from the environment!"));
                }
            }
            else
            {
                return(new ValidationResult(false, GetErrorStringForUnrecognizedUnit(unitString)));
            }
        }
Exemplo n.º 33
0
 public static SIPrefix GetSIPrefix(Unit unit, double value, SIPrefix minimumPrefix, SIPrefix maximumPrefix, SIPrefix defaultPrefix, int signiFicantDigits = 15)
 {
     if (unit == Unit.DegreeAngle || unit == Unit.Percent || unit == Unit.None)
     {
         return SIPrefix.None;
     }
     if (Math.Abs(value) > Double.Epsilon)
     {
         value = Math.Abs(value);
         var prefixBase = 3 * unit.PrefixExponent;
         double significantDigitsBias = 1;
         if (signiFicantDigits < Math.Abs(3 * unit.PrefixExponent))
         {
             significantDigitsBias = Math.Pow(10, Math.Abs(3 * unit.PrefixExponent - signiFicantDigits));
         }
         var exponent = (int)Math.Floor((Math.Log10(value * significantDigitsBias)) / prefixBase) * prefixBase;
         return PrefixFromExponent(exponent / unit.PrefixExponent, minimumPrefix, maximumPrefix);
     }
     //use the more suitable prefix from limits for value == 0.0
     return (SIPrefix)Math.Max((int)minimumPrefix, Math.Min((int)defaultPrefix, (int)maximumPrefix));
 }