/// <summary>
        ///     Parse a string of the format "&lt;quantity&gt; &lt;unit&gt;".
        /// </summary>
        /// <example>
        ///     Length.Parse("5.5 m", new CultureInfo("en-US"));
        /// </example>
        /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
        /// <exception cref="ArgumentException">
        ///     Expected 2 words. Input string needs to be in the format "&lt;quantity&gt; &lt;unit
        ///     &gt;".
        /// </exception>
        /// <exception cref="UnitsNetException">Error parsing string.</exception>
        public static Acceleration Parse(string str, IFormatProvider formatProvider = null)
        {
            if (str == null)
            {
                throw new ArgumentNullException("str");
            }

            var numFormat = formatProvider != null ?
                            (NumberFormatInfo)formatProvider.GetFormat(typeof(NumberFormatInfo)) :
                            NumberFormatInfo.CurrentInfo;

            var numRegex = string.Format(@"[\d., {0}{1}]*\d",               // allows digits, dots, commas, and spaces in the quantity (must end in digit)
                                         numFormat.NumberGroupSeparator,    // adds provided (or current) culture's group separator
                                         numFormat.NumberDecimalSeparator); // adds provided (or current) culture's decimal separator
            var regexString = string.Format("(?<value>[-+]?{0}{1}{2}{3}",
                                            numRegex,                       // capture base (integral) Quantity value
                                            @"(?:[eE][-+]?\d+)?)",          // capture exponential (if any), end of Quantity capturing
                                            @"\s?",                         // ignore whitespace (allows both "1kg", "1 kg")
                                            @"(?<unit>\S+)");               // capture Unit (non-whitespace) input

            var             regex  = new Regex(regexString);
            GroupCollection groups = regex.Match(str.Trim()).Groups;

            var valueString = groups["value"].Value;
            var unitString  = groups["unit"].Value;

            if (valueString == "" || unitString == "")
            {
                var ex = new ArgumentException(
                    "Expected valid quantity and unit. Input string needs to be in the format \"<quantity><unit> or <quantity> <unit>\".", "str");
                ex.Data["input"]          = str;
                ex.Data["formatprovider"] = formatProvider == null ? null : formatProvider.ToString();
                throw ex;
            }

            try
            {
                AccelerationUnit unit  = ParseUnit(unitString, formatProvider);
                double           value = double.Parse(valueString, formatProvider);

                return(From(value, unit));
            }
            catch (Exception e)
            {
                var newEx = new UnitsNetException("Error parsing string.", e);
                newEx.Data["input"]          = str;
                newEx.Data["formatprovider"] = formatProvider == null ? null : formatProvider.ToString();
                throw newEx;
            }
        }
Exemple #2
0
        /// <summary>
        ///     Parse a string given a particular regular expression.
        /// </summary>
        /// <exception cref="UnitsNetException">Error parsing string.</exception>
        private static List <Angle> ParseWithRegex(string regexString, string str, IFormatProvider formatProvider = null)
        {
            var             regex     = new Regex(regexString);
            MatchCollection matches   = regex.Matches(str.Trim());
            var             converted = new List <Angle>();

            foreach (Match match in matches)
            {
                GroupCollection groups = match.Groups;

                var valueString = groups["value"].Value;
                var unitString  = groups["unit"].Value;
                if (groups["invalid"].Value != "")
                {
                    var newEx = new UnitsNetException("Invalid string detected: " + groups["invalid"].Value);
                    newEx.Data["input"]          = str;
                    newEx.Data["matched value"]  = valueString;
                    newEx.Data["matched unit"]   = unitString;
                    newEx.Data["formatprovider"] = formatProvider == null ? null : formatProvider.ToString();
                    throw newEx;
                }
                if (valueString == "" && unitString == "")
                {
                    continue;
                }

                try
                {
                    AngleUnit unit  = ParseUnit(unitString, formatProvider);
                    double    value = double.Parse(valueString, formatProvider);

                    converted.Add(From(value, unit));
                }
                catch (AmbiguousUnitParseException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    var newEx = new UnitsNetException("Error parsing string.", ex);
                    newEx.Data["input"]          = str;
                    newEx.Data["matched value"]  = valueString;
                    newEx.Data["matched unit"]   = unitString;
                    newEx.Data["formatprovider"] = formatProvider == null ? null : formatProvider.ToString();
                    throw newEx;
                }
            }
            return(converted);
        }
        public static DynamicDateFormatInfo GetInstance(string calendarModelId, IFormatProvider provider = null)
        {
            if (provider == null)
            {
                provider = CultureInfo.CurrentCulture;
            }
            string cInfId = calendarModelId + "_" + provider.ToString();

            if (infoCacheS.ContainsKey(cInfId))
            {
                return(infoCacheS[cInfId]);
            }
            DateTimeFormatInfo x = DateTimeFormatInfo.GetInstance(provider);
            var inf = new DynamicDateFormatInfo(x);

            if (string.IsNullOrEmpty(calendarModelId))
            {
                return((DynamicDateFormatInfo)inf.Clone());
            }

            var model = DynamicCalendarModel.GetCachedModel(calendarModelId);

            if (model != null && model.FormatInfo != null)
            {
                inf.CalendarModelID = calendarModelId;

                var mi = model.FormatInfo;
                inf.Import(mi);
            }

            return(inf);
        }
            /// <inheritdoc />
            public string ToString(string format, IFormatProvider formatProvider)
            {
                if (format != null)
                {
                    throw new ArgumentOutOfRangeException(nameof(format), "format should be null");
                }

                return(formatProvider.ToString());
            }
Exemple #5
0
 public string FormattedCurrency()
 {
     if (formatProvider.ToString().Equals("en-US"))
     {
         return(this.Currency < 0 ? this.Currency.ToString("C", formatProvider) : (this.Currency).ToString("C", formatProvider));
     }
     else
     {
         return(this.Currency < 0 ? "- " + Math.Abs(this.Currency).ToString("C", formatProvider) : (this.Currency).ToString("C", formatProvider));
     }
 }
Exemple #6
0
        /// <summary>
        ///     Parse a unit string.
        /// </summary>
        /// <example>
        ///     Length.ParseUnit("m", new CultureInfo("en-US"));
        /// </example>
        /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
        /// <exception cref="UnitsNetException">Error parsing string.</exception>
        public static RatioUnit ParseUnit(string str, IFormatProvider formatProvider = null)
        {
            if (str == null)
            {
                throw new ArgumentNullException("str");
            }
            var unitSystem = UnitSystem.GetCached(formatProvider);

            var unit = unitSystem.Parse <RatioUnit>(str.Trim());

            if (unit == RatioUnit.Undefined)
            {
                var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RatioUnit.");
                newEx.Data["input"]          = str;
                newEx.Data["formatprovider"] = formatProvider == null ? null : formatProvider.ToString();
                throw newEx;
            }

            return(unit);
        }
Exemple #7
0
        /// <summary>
        ///     Parse a unit string.
        /// </summary>
        /// <param name="str">String to parse. Typically in the form: {number} {unit}</param>
        /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="UnitSystem.DefaultCulture" />.</param>
        /// <example>
        ///     Length.ParseUnit("m", new CultureInfo("en-US"));
        /// </example>
        /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception>
        /// <exception cref="UnitsNetException">Error parsing string.</exception>
        internal static RotationalSpeedUnit ParseUnit(string str, IFormatProvider provider = null)
        {
            if (str == null)
            {
                throw new ArgumentNullException(nameof(str));
            }

            var unitSystem = UnitSystem.GetCached(provider);
            var unit       = unitSystem.Parse <RotationalSpeedUnit>(str.Trim());

            if (unit == RotationalSpeedUnit.Undefined)
            {
                var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized RotationalSpeedUnit.");
                newEx.Data["input"]    = str;
                newEx.Data["provider"] = provider?.ToString() ?? "(null)";
                throw newEx;
            }

            return(unit);
        }
Exemple #8
0
        static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, IFormatProvider formatProvider = null)
        {
            if (str == null)
            {
                throw new ArgumentNullException("str");
            }

            var unitSystem = UnitSystem.GetCached(formatProvider);
            var unit       = unitSystem.Parse <BrakeSpecificFuelConsumptionUnit>(str.Trim());

            if (unit == BrakeSpecificFuelConsumptionUnit.Undefined)
            {
                var newEx = new UnitsNetException("Error parsing string. The unit is not a recognized BrakeSpecificFuelConsumptionUnit.");
                newEx.Data["input"]          = str;
                newEx.Data["formatprovider"] = formatProvider?.ToString() ?? "(null)";
                throw newEx;
            }

            return(unit);
        }
        /// <summary>
        /// Formats the message for the TypeConversionException
        /// </summary>
        /// <param name="value">The value that the user tried to convert</param>
        /// <param name="defaultValue">The default value used</param>
        /// <param name="targetType">The target type</param>
        /// <param name="format">The format provider</param>
        /// <returns>A string containing the message for the generated TypeConversionException</returns>
        public static string FormatTypeConversionExceptionMesssage(object value, object defaultValue, Type targetType, IFormatProvider format)
        {
            string valueTypeName = (value != null) ? value.GetType().ToString() : "(undefined type)";
            string valueString   = (value != null) ? (IsDBNull(value) ? "[NULL]" : value.ToString()) : "(null)";

            string defaultValueTypeName = (defaultValue != null) ? defaultValue.GetType().ToString() : "(undefined type)";
            string defaultValueString   = (defaultValue != null) ? (IsDBNull(defaultValue) ? "[NULL]" : defaultValue.ToString()) : "(null)";

            string targetTypeName = (targetType != null) ? targetType.ToString() : "(undefined type)";

            string formatProviderTypeName = (format != null) ? format.GetType().ToString() : "(undefined type)";
            string cultureName            = (format != null) ? format.ToString() : string.Empty;

            return(string.Format(
                       "Error(s) occured while trying to convert value '{0}' (of type '{1}') to type '{2}' using default value '{3}' (of type '{4}') and format provider '{5}' (of type '{6}')",
                       valueString,
                       valueTypeName,
                       targetTypeName,
                       defaultValueString,
                       defaultValueString,
                       cultureName,
                       formatProviderTypeName));
        }
    private string GetDataString(string strSrc, IFormatProvider provider)
    {
        string str1, str2, str;
        int    len1;

        if (null == strSrc)
        {
            str1 = "null";
            len1 = 0;
        }
        else
        {
            str1 = strSrc;
            len1 = strSrc.Length;
        }

        str2 = (null == provider) ? "null" : provider.ToString();

        str  = string.Format("\n[Source string value]\n \"{0}\"", str1);
        str += string.Format("\n[Length of source string]\n {0}", len1);
        str += string.Format("\n[Format provider string]\n {0}", str2);

        return(str);
    }
		/// <summary>
		/// Formats the message for the TypeConversionException
		/// </summary>
		/// <param name="value">The value that the user tried to convert</param>
		/// <param name="defaultValue">The default value used</param>
		/// <param name="targetType">The target type</param>
		/// <param name="format">The format provider</param>
		/// <returns>A string containing the message for the generated TypeConversionException</returns>
		public static string FormatTypeConversionExceptionMesssage(object value, object defaultValue, Type targetType, IFormatProvider format)
		{
			string valueTypeName = (value != null) ? value.GetType().ToString() : "(undefined type)";
			string valueString = (value != null) ? (IsDBNull(value) ? "[NULL]" : value.ToString()) : "(null)";

			string defaultValueTypeName = (defaultValue != null) ? defaultValue.GetType().ToString() : "(undefined type)";
			string defaultValueString = (defaultValue != null) ? (IsDBNull(defaultValue) ? "[NULL]" : defaultValue.ToString()) : "(null)";

			string targetTypeName = (targetType != null) ? targetType.ToString() : "(undefined type)";

			string formatProviderTypeName = (format != null) ? format.GetType().ToString() : "(undefined type)";
			string cultureName = (format != null) ? format.ToString() : string.Empty;

			return string.Format(
				"Error(s) occured while trying to convert value '{0}' (of type '{1}') to type '{2}' using default value '{3}' (of type '{4}') and format provider '{5}' (of type '{6}')",
				valueString,
				valueTypeName,
				targetTypeName,
				defaultValueString,
				defaultValueString,
				cultureName,
				formatProviderTypeName);
		}
    private string GetDataString(string strSrc, IFormatProvider provider)
    {
        string str1, str2, str;
        int len1;

        if (null == strSrc)
        {
            str1 = "null";
            len1 = 0;
        }
        else
        {
            str1 = strSrc;
            len1 = strSrc.Length;
        }

        str2 = (null == provider) ? "null" : provider.ToString();

        str = string.Format("\n[Source string value]\n \"{0}\"", str1);
        str += string.Format("\n[Length of source string]\n {0}", len1);
        str += string.Format("\n[Format provider string]\n {0}", str2);

        return str;
    }
Exemple #13
0
 public override string ToString()
 {
     return(base.ToString() + " - " + GetNumberFormat() + " - " + formatProvider.ToString());
 }