예제 #1
0
 /// <summary>
 /// Constructor. These units are created together and passed around to make conversions easier
 /// </summary>
 /// <param name="volU"></param>
 /// <param name="arU"></param>
 /// <param name="vertU"></param>
 /// <param name="horU"></param>
 public UnitGroup(VolumeUnit volU, AreaUnit arU, LengthUnit vertU, LengthUnit horU)
 {
     VolUnit   = volU;
     ArUnit    = arU;
     VertUnit  = vertU;
     HorizUnit = horU;
 }
예제 #2
0
        public string ToString(VolumeUnit unit, [CanBeNull] string cultureName, int significantDigitsAfterRadix)
        {
            double value  = As(unit);
            string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix);

            return(ToString(unit, cultureName, format));
        }
        public void Parse(string text, double value, VolumeUnit unit)
        {
            Measurement <VolumeUnit> .TryParse(CultureInfo.InvariantCulture, text, out Measurement <VolumeUnit> v).Should().BeTrue();

            v.Value.Should().BeApproximately(value, 1e-10);
            v.Unit.Should().Be(unit);
        }
예제 #4
0
        public override Volume ConvertTo(VolumeUnit unitTo)
        {
            switch (unitTo)
            {
            case VolumeUnit.Quarts:
            {
                return(new USQuart(Value * 4M));
            }

            case VolumeUnit.Gallons:
            {
                return(new USGallon(Value));
            }

            case VolumeUnit.Litres:
            {
                return(new Litre(Value * 3.78541M));
            }

            default:
            {
                throw new Exception(String.Format("Volume unit {0} is unknown.", unitTo.GetType().Name));
            }
            }
        }
예제 #5
0
        public static string GetAbbreviation(VolumeUnit unit, [CanBeNull] string cultureName)
        {
            // Windows Runtime Component does not support CultureInfo and IFormatProvider types, so we use culture name for public methods: https://msdn.microsoft.com/en-us/library/br230301.aspx
            IFormatProvider provider = cultureName == null ? UnitSystem.DefaultCulture : new CultureInfo(cultureName);

            return(UnitSystem.GetCached(provider).GetDefaultAbbreviation(unit));
        }
예제 #6
0
        public void DeserializeCustomUnitAsPredefined_ShouldReturnValidResult()
        {
            // arrange
            var someUnit = new VolumeUnit(
                name: "some unit",
                abbreviation: "su",
                valueInCubicMetres: (number)123.456m);
            string json      = @"{
  'unit': 'su'
}";
            var    converter = new VolumeUnitJsonConverter(
                serializationFormat: LinearUnitJsonSerializationFormat.PredefinedAsString,
                tryReadCustomPredefinedUnit: (string value, out VolumeUnit predefinedUnit) =>
            {
                if (value == someUnit.Abbreviation)
                {
                    predefinedUnit = someUnit;
                    return(true);
                }

                predefinedUnit = default(VolumeUnit);
                return(false);
            });

            // act
            var result = JsonConvert.DeserializeObject <SomeUnitOwner <VolumeUnit> >(json, converter);

            // assert
            result.Unit.Should().Be(someUnit);
        }
예제 #7
0
 public RechnParameters(long ca, double bd, double fc, VolumeUnit un)
 {
     CellArea     = ca;
     BaseDelta    = bd;
     FluidContact = fc;
     unit         = un;
 }
예제 #8
0
 public UnitSystem()
 {
     this.temperature        = TemperatureUnit.Celsius;
     this.pressure           = PressureUnit.Pascal;
     this.massFlowRate       = MassFlowRateUnit.KgPerSec;
     this.volumeFlowRate     = VolumeFlowRateUnit.CubicMeterPerSec;
     this.moistureContent    = MoistureContentUnit.KgPerKg;
     this.relativeHumidity   = RatioUnit.Percent;
     this.enthalpy           = SpecificEnergyUnit.JoulePerKg;
     this.specificHeat       = SpecificHeatUnit.JoulePerKgKelvin;
     this.energy             = EnergyUnit.Joule;
     this.power              = PowerUnit.JoulePerSec;
     this.density            = DensityUnit.KgPerCubicMeter;
     this.dynamicViscosity   = DynamicViscosityUnit.PascalSecond;
     this.kinematicViscosity = KinematicViscosityUnit.SquareMeterPerSec;
     this.conductivity       = ThermalConductivityUnit.WattPerMeterKelvin;
     this.diffusivity        = DiffusivityUnit.SquareMeterPerSec;
     this.mass     = MassUnit.Kilogram;
     this.length   = LengthUnit.Meter;
     this.area     = AreaUnit.SquareMeter;
     this.volume   = VolumeUnit.CubicMeter;
     this.time     = TimeUnit.Second;
     this.Name     = "SI"; //ep
     this.readOnly = true;
 }
예제 #9
0
        //HeatFluxDensityUnit heatTransferCoefficient;
        //ForceUnit force;
        //SurfaceTensionUnit surfaceTension;

        public UnitSystem(TemperatureUnit temperature, PressureUnit pressure, MassFlowRateUnit massFlowRate,
                          VolumeFlowRateUnit volumeFlowRate, MoistureContentUnit moistureContent,
                          RatioUnit relativeHumidity, SpecificEnergyUnit enthalpy,
                          SpecificHeatUnit specificHeat, EnergyUnit energy, PowerUnit power, DensityUnit density,
                          DynamicViscosityUnit dynamicViscosity, KinematicViscosityUnit kinematicViscosity,
                          ThermalConductivityUnit conductivity, DiffusivityUnit diffusivity, MassUnit mass,
                          LengthUnit length, AreaUnit area, VolumeUnit volume, TimeUnit Time, string name) //ep
        {
            this.temperature        = temperature;
            this.pressure           = pressure;
            this.massFlowRate       = massFlowRate;
            this.volumeFlowRate     = volumeFlowRate;
            this.moistureContent    = moistureContent;
            this.relativeHumidity   = relativeHumidity;
            this.enthalpy           = enthalpy;
            this.specificHeat       = specificHeat;
            this.energy             = energy;
            this.power              = power;
            this.density            = density;
            this.dynamicViscosity   = dynamicViscosity;
            this.kinematicViscosity = kinematicViscosity;
            this.conductivity       = conductivity;
            this.diffusivity        = diffusivity;
            this.mass     = mass;
            this.length   = length;
            this.area     = area;
            this.volume   = volume;
            this.time     = time;
            this.Name     = name;  //ep
            this.readOnly = false; //ep
        }
예제 #10
0
        public string ToString(VolumeUnit unit, [CanBeNull] IFormatProvider provider, int significantDigitsAfterRadix)
        {
            double value  = As(unit);
            string format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix);

            return(ToString(unit, provider, format));
        }
예제 #11
0
파일: ToGBXML.cs 프로젝트: BHoM/XML_Toolkit
        private static string ToGBX(this VolumeUnit volumeUnit)
        {
            switch (volumeUnit)
            {
            case VolumeUnit.CubicCentimeters:
                return("CubicCentimeters");

            case VolumeUnit.CubicFeet:
                return("CubicFeet");

            case VolumeUnit.CubicInches:
                return("CubicInches");

            case VolumeUnit.CubicKilometers:
                return("CubicKilometers");

            case VolumeUnit.CubicMeters:
                return("CubicMeters");

            case VolumeUnit.CubicMiles:
                return("CubicMiles");

            case VolumeUnit.CubicMillimeters:
                return("CubicMillimeters");

            case VolumeUnit.CubicYards:
                return("CubicYards");

            default:
                return("CubicMeters");
            }
        }
예제 #12
0
        /// <summary>
        /// Method to convert one volume to another
        /// </summary>
        /// <param name="unit">defines which unit used</param>
        /// <param name="volume">volume for conversion</param>
        /// <returns>returns value after calculation</returns>
        public double ConvertVolumes(VolumeUnit unit, double volume)
        {
            try
            {
                if (unit.Equals(VolumeUnit.GallonToLiter))
                {
                    return(volume * GallonToLiter);
                }

                if (unit.Equals(VolumeUnit.LiterToMilliliter))
                {
                    return(volume * LiterToMilliliter);
                }

                if (unit.Equals(VolumeUnit.MilliliterToLiter))
                {
                    return(volume / MilliliterToLiter);
                }

                return(volume);
            }
            catch (QuantityException e)
            {
                throw new QuantityException(QuantityException.ExceptionType.InvalidData, e.Message);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
예제 #13
0
파일: Volume.g.cs 프로젝트: apkbox/UnitsNet
        public string ToString(VolumeUnit unit, CultureInfo culture, string format, params object[] args)
        {
            string abbreviation = UnitSystem.GetCached(culture).GetDefaultAbbreviation(unit);

            object[] finalArgs = new object[] { As(unit), abbreviation }
            .Concat(args)
            .ToArray();

            return(string.Format(culture, format, finalArgs));
        }
예제 #14
0
        /// <summary>
        ///     Convert to the unit representation <paramref name="unit" />.
        /// </summary>
        /// <returns>Value converted to the specified unit.</returns>
        public double As(VolumeUnit unit)
        {
            if (Unit == unit)
            {
                return(Convert.ToDouble(Value));
            }

            var converted = AsBaseNumericType(unit);

            return(Convert.ToDouble(converted));
        }
            public void ShouldConvertToExpectedValue(Volume originalVolume, VolumeUnit targetUnit, Volume expectedVolume)
            {
                // arrange
                // act
                var actualVolume = originalVolume.Convert(targetUnit);

                // assert
                actualVolume.CubicMetres.Should().BeApproximately(expectedVolume.CubicMetres);
                actualVolume.Value.Should().BeApproximately(expectedVolume.Value);
                actualVolume.Unit.Should().Be(targetUnit);
            }
예제 #16
0
            public void ParamlessConstructedVolumeUnit_ShouldBeEqualToMetre()
            {
                // arrange
                var paramlessConstructedVolumeUnit = new VolumeUnit();
                var metre = VolumeUnit.CubicMetre;

                // act
                // assert
                metre.Equals(paramlessConstructedVolumeUnit).Should().BeTrue(because: "'VolumeUnit.CubicMetre' should be equal 'new VolumeUnit()'");
                paramlessConstructedVolumeUnit.Equals(metre).Should().BeTrue(because: "'new VolumeUnit()' should be equal 'VolumeUnit.CubicMetre'");
            }
예제 #17
0
 public static string ToDisplayStringInShort(this VolumeUnit volumeUnit)
 {
     try
     {
         return(FactoryUnits.GetShortDisplayString(UnitsType.Volume, (int)volumeUnit));
     }
     catch (InvalidOperationException)
     {
         throw new ArgumentOutOfRangeException(/*MSG0*/ "volumeUnit");
     }
 }
예제 #18
0
 protected void ToString(List <string> toStringOutput)
 {
     toStringOutput.Add($"CustomUnit = {(CustomUnit == null ? "null" : CustomUnit.ToString())}");
     toStringOutput.Add($"AreaUnit = {(AreaUnit == null ? "null" : AreaUnit.ToString())}");
     toStringOutput.Add($"LengthUnit = {(LengthUnit == null ? "null" : LengthUnit.ToString())}");
     toStringOutput.Add($"VolumeUnit = {(VolumeUnit == null ? "null" : VolumeUnit.ToString())}");
     toStringOutput.Add($"WeightUnit = {(WeightUnit == null ? "null" : WeightUnit.ToString())}");
     toStringOutput.Add($"GenericUnit = {(GenericUnit == null ? "null" : GenericUnit.ToString())}");
     toStringOutput.Add($"TimeUnit = {(TimeUnit == null ? "null" : TimeUnit.ToString())}");
     toStringOutput.Add($"Type = {(Type == null ? "null" : Type.ToString())}");
 }
예제 #19
0
 public double As(VolumeUnit unit)
 {
     if (this.unit == unit)
     {
         return(internalValue);
     }
     else
     {
         double f = Factor(this.unit) / Factor(unit);
         return(internalValue * f);
     }
 }
예제 #20
0
                    6, MassUnit.Kilogram)]  // synthetic data
        public static void ComponentMassFromMassConcentrationAndSolutionVolume(
            double massConcValue, MassConcentrationUnit massConcUnit,
            double volumeValue, VolumeUnit volumeUnit,
            double expectedMassValue, MassUnit expectedMassUnit, double tolerance = 1e-5)
        {
            var massConcentration = new MassConcentration(massConcValue, massConcUnit);
            var volume            = new Volume(volumeValue, volumeUnit);

            Mass massComponent = massConcentration * volume;

            AssertEx.EqualTolerance(expectedMassValue, massComponent.As(expectedMassUnit), tolerance);
        }
예제 #21
0
        /// <summary>
        /// Converts the specified from unit to the specified unit.
        /// </summary>
        /// <param name="fromUnit">Covert from unit.</param>
        /// <param name="toUnit">Covert to unit.</param>
        /// <param name="fromValue">Covert from value.</param>
        /// <returns>The converted value.</returns>
        public static double Convert(
            VolumeUnit fromUnit,
            VolumeUnit toUnit,
            double fromValue)
        {
            if (fromUnit == toUnit)
                return fromValue;

            double fromFactor = factors[(int)fromUnit];
            double toFactor = factors[(int)toUnit];
            double result = fromFactor * fromValue / toFactor;
            return result;
        }
예제 #22
0
        /// <summary>
        /// Normalize by changing the unit.
        /// This method will only change to a unit in the same system and only to commonly used units.
        /// </summary>
        public void Normalize()
        {
            if (System != VolumeSystem.Special)
            {
                VolumeUnit min, max;
                switch (System)
                {
                case VolumeSystem.MetricSolid:
                    min = UNIT_IDX_METRIC_SOLID_MIN;
                    max = UNIT_IDX_METRIC_SOLID_MAX_STD;
                    break;

                case VolumeSystem.MetricLiquid:
                    min = UNIT_IDX_METRIC_LIQUID_MIN;
                    max = UNIT_IDX_METRIC_LIQUID_MAX_STD;
                    break;

                case VolumeSystem.ImperialSolid:
                    min = UNIT_IDX_IMPERIAL_SOLID_MIN;
                    max = UNIT_IDX_IMPERIAL_SOLID_MAX_STD;
                    break;

                case VolumeSystem.ImperialLiquid:
                    min = UNIT_IDX_IMPERIAL_LIQUID_MIN;
                    max = UNIT_IDX_IMPERIAL_LIQUID_MAX_STD;
                    break;

                default:
                    return;
                }
                if (internalValue != 0)
                {
                    double log = Math.Log10(internalValue);
                    double f   = Factor(unit);
                    for (VolumeUnit u = max; u >= min; u--)
                    {
                        double log_new = Math.Log10(f / Factor(u));
                        if (log + log_new >= 0)
                        {
                            Unit = u;
                            break;
                        }
                    }
                }
                else if (IsMetric)
                {
                    unit = SI;
                }
            }
        }
예제 #23
0
        public void DeserializePredefinedUnitString_ShouldReturnValidResult(VolumeUnit expectedUnit)
        {
            // arrange
            string json      = $@"{{
  'unit': '{expectedUnit.Abbreviation}'
}}";
            var    converter = new VolumeUnitJsonConverter();

            // act
            var result = JsonConvert.DeserializeObject <SomeUnitOwner <VolumeUnit> >(json, converter);

            // assert
            result.Unit.Should().Be(expectedUnit);
        }
예제 #24
0
        /// <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 Volume 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
            {
                VolumeUnit 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;
            }
        }
예제 #25
0
        /// <summary>
        /// Converts the <see cref="Volume"/> to the specified <paramref name="targetUnit"/>.
        /// </summary>
        /// <param name="targetUnit">Target units.</param>
        /// <returns><see cref="Volume"/> converted to <paramref name="targetUnit"/>.</returns>
        public double ConvertTo(VolumeUnit targetUnit)
        {
            switch (targetUnit)
            {
            case VolumeUnit.CubicMeters:
                return(m_value);

            case VolumeUnit.Liters:
                return(ToLiters());

            case VolumeUnit.Teaspoons:
                return(ToTeaspoons());

            case VolumeUnit.MetricTeaspoons:
                return(ToMetricTeaspoons());

            case VolumeUnit.Tablespoons:
                return(ToTablespoons());

            case VolumeUnit.MetricTablespoons:
                return(ToMetricTablespoons());

            case VolumeUnit.Cups:
                return(ToCups());

            case VolumeUnit.MetricCups:
                return(ToMetricCups());

            case VolumeUnit.FluidOunces:
                return(ToFluidOunces());

            case VolumeUnit.Pints:
                return(ToPints());

            case VolumeUnit.Quarts:
                return(ToQuarts());

            case VolumeUnit.Gallons:
                return(ToGallons());

            case VolumeUnit.CubicInches:
                return(ToCubicInches());

            case VolumeUnit.CubicFeet:
                return(ToCubicFeet());

            default:
                throw new ArgumentOutOfRangeException(nameof(targetUnit), targetUnit, null);
            }
        }
예제 #26
0
        /// <summary>
        /// Converts the <paramref name="value"/> in the specified <paramref name="sourceUnit"/> to a new <see cref="Volume"/> in cubic meters.
        /// </summary>
        /// <param name="value">Source value.</param>
        /// <param name="sourceUnit">Source value units.</param>
        /// <returns>New <see cref="Volume"/> from the specified <paramref name="value"/> in <paramref name="sourceUnit"/>.</returns>
        public static Volume ConvertFrom(double value, VolumeUnit sourceUnit)
        {
            switch (sourceUnit)
            {
            case VolumeUnit.CubicMeters:
                return(value);

            case VolumeUnit.Liters:
                return(FromLiters(value));

            case VolumeUnit.Teaspoons:
                return(FromTeaspoons(value));

            case VolumeUnit.MetricTeaspoons:
                return(FromMetricTeaspoons(value));

            case VolumeUnit.Tablespoons:
                return(FromTablespoons(value));

            case VolumeUnit.MetricTablespoons:
                return(FromMetricTablespoons(value));

            case VolumeUnit.Cups:
                return(FromCups(value));

            case VolumeUnit.MetricCups:
                return(FromMetricCups(value));

            case VolumeUnit.FluidOunces:
                return(FromFluidOunces(value));

            case VolumeUnit.Pints:
                return(FromPints(value));

            case VolumeUnit.Quarts:
                return(FromQuarts(value));

            case VolumeUnit.Gallons:
                return(FromGallons(value));

            case VolumeUnit.CubicInches:
                return(FromCubicInches(value));

            case VolumeUnit.CubicFeet:
                return(FromCubicFeet(value));

            default:
                throw new ArgumentOutOfRangeException(nameof(sourceUnit), sourceUnit, null);
            }
        }
예제 #27
0
        /// <summary>
        ///     Parse a string given a particular regular expression.
        /// </summary>
        /// <exception cref="UnitsNetException">Error parsing string.</exception>
        private static List <Volume> ParseWithRegex(string regexString, string str, IFormatProvider formatProvider = null)
        {
            var             regex     = new Regex(regexString);
            MatchCollection matches   = regex.Matches(str.Trim());
            var             converted = new List <Volume>();

            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
                {
                    VolumeUnit unit  = ParseUnit(unitString, formatProvider);
                    double     value = double.Parse(valueString, formatProvider);

                    converted.Add(From(value, unit));
                }
                catch (AmbiguousUnitParseException ambiguousException)
                {
                    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);
        }
예제 #28
0
                    0.1142805, MolarityUnit.MolesPerLiter)]     // molarity(HCl) = 5g / (1.2L * 36.46) = 0.114 mol/l = 0.114 M
        public void MolarityFromComponentMassAndSolutionVolume(
            double componentMassValue, MassUnit componentMassUnit,
            double componentMolarMassValue, MolarMassUnit componentMolarMassUnit,
            double solutionVolumeValue, VolumeUnit solutionVolumeUnit,
            double expectedMolarityValue, MolarityUnit expectedMolarityUnit, double tolerence = 1e-5)
        {
            var componentMass      = new Mass(componentMassValue, componentMassUnit);
            var componentMolarMass = new MolarMass(componentMolarMassValue, componentMolarMassUnit);
            var volumeSolution     = new Volume(solutionVolumeValue, solutionVolumeUnit);
            AmountOfSubstance amountOfSubstance = componentMass / componentMolarMass;

            Molarity molarity = amountOfSubstance / volumeSolution;

            AssertEx.EqualTolerance(expectedMolarityValue, molarity.As(expectedMolarityUnit), tolerence);
        }
예제 #29
0
                    1.2, VolumeUnit.Liter)]     // 1.2 L of solution required for obtaining 0.1142805 Moles/L from 5g HCl
        public void VolumeSolutionFromComponentMassAndDesiredConcentration(
            double componentMassValue, MassUnit componentMassUnit,
            double componentMolarMassValue, MolarMassUnit componentMolarMassUnit,
            double desiredMolarityValue, MolarityUnit desiredMolarityUnit,
            double expectedSolutionVolumeValue, VolumeUnit expectedSolutionVolumeUnit, double tolerence = 1e-5)
        {
            var componentMass      = new Mass(componentMassValue, componentMassUnit);
            var componentMolarMass = new MolarMass(componentMolarMassValue, componentMolarMassUnit);
            var desiredMolarity    = new Molarity(desiredMolarityValue, desiredMolarityUnit);
            AmountOfSubstance amountOfSubstance = componentMass / componentMolarMass;

            Volume volumeSolution = amountOfSubstance / desiredMolarity;

            AssertEx.EqualTolerance(expectedSolutionVolumeValue, volumeSolution.As(expectedSolutionVolumeUnit), tolerence);
        }
예제 #30
0
        /// <summary>
        /// Converts the specified from unit to the specified unit.
        /// </summary>
        /// <param name="fromUnit">Covert from unit.</param>
        /// <param name="toUnit">Covert to unit.</param>
        /// <param name="fromValue">Covert from value.</param>
        /// <returns>The converted value.</returns>
        public static double Convert(
            VolumeUnit fromUnit,
            VolumeUnit toUnit,
            double fromValue)
        {
            if (fromUnit == toUnit)
            {
                return(fromValue);
            }

            double fromFactor = factors[(int)fromUnit];
            double toFactor   = factors[(int)toUnit];
            double result     = fromFactor * fromValue / toFactor;

            return(result);
        }
예제 #31
0
        private void ddVolume_OnSelectedIndexChange(object sender, EventArgs e)
        {
            if (ddTankVolume.SelectedItem != null)
            {
                var newUnit = UnitParser.ParseVolumeUnit((string)ddTankVolume.SelectedItem);

                _mVolumeValue = ddTankVolume.ConvertValue(_mActiveVolumeUnit, newUnit, _mVolumeValue);
                if (!double.IsNaN(_mVolumeValue))
                {
                    tbVolume.Text = Parsing.DoubleToString(_mVolumeValue);
                }

                _mActiveVolumeUnit            = newUnit;
                Settings.Default.TMVolumeUnit = _mActiveVolumeUnit.ToString();
            }
        }
        public Volume Convert(Volume from, VolumeUnit to) {
            if (from.Unit.Equals(to))
                return new Volume(from.Amount, to);

            if (from.Unit.Equals(VolumeUnit.Liters) && to.Equals(VolumeUnit.Gallons))
                return new Volume(from.Amount * _gals_In_1_Ltr, to);
            if (from.Unit.Equals(VolumeUnit.Gallons) && to.Equals(VolumeUnit.Liters))
                return new Volume(from.Amount / _gals_In_1_Ltr, to);
            if (from.Unit.Equals(VolumeUnit.Liters) && to.Equals(VolumeUnit.Barrels))
                return new Volume(from.Amount * _brls_In_1_Ltr, to);
            if (from.Unit.Equals(VolumeUnit.Barrels) && to.Equals(VolumeUnit.Liters))
                return new Volume(from.Amount / _brls_In_1_Ltr, to);
            if (from.Unit.Equals(VolumeUnit.Barrels) && to.Equals(VolumeUnit.Gallons))
                return new Volume(from.Amount * _gals_In_1_Brl, to);
            if (from.Unit.Equals(VolumeUnit.Gallons) && to.Equals(VolumeUnit.Barrels))
                return new Volume(from.Amount / _gals_In_1_Brl, to);
            throw new NotImplementedException();
        }
예제 #33
0
파일: Litre.cs 프로젝트: Jonsey/Dymensions
 public override Volume ConvertTo(VolumeUnit unitTo)
 {
     switch (unitTo)
     {
         case VolumeUnit.Quarts:
             {
                 return new USQuart(Value * 1.05669M);
             }
         case VolumeUnit.Gallons:
             {
                 return new USGallon(Value * 0.264172M);
             }
         case VolumeUnit.Litres:
             {
                 return new Litre(Value);
             }
         default:
             {
                 throw new Exception(String.Format("Volume unit {0} is unknown.", unitTo.GetType().Name));
             }
     }
 }
 protected static string CreateSuffix(SymbolFormat format, VolumeUnit unit)
 {
     return default(Volume).ToString(unit, format).Trim('0');
 }
예제 #35
0
파일: Volume.cs 프로젝트: Jonsey/Dymensions
 public Volume(decimal value, VolumeUnit unit)
 {
     Value = value;
     Unit = unit;
 }
예제 #36
0
파일: Volume.cs 프로젝트: Jonsey/Dymensions
 public virtual Volume ConvertTo(VolumeUnit unitTo)
 {
     var volume = GetInstanceOfCurrentVolume();
     return volume.ConvertTo(unitTo);
 }
 protected abstract VolumeUnit __DoSubstraction(VolumeUnit right);
 protected abstract VolumeUnit __DoAddition(VolumeUnit right);
 protected override VolumeUnit __DoSubstraction(VolumeUnit right)
 {
     return new Meter3(ConvertToBase().Value - right.ConvertToBase().Value);
 }
 protected override VolumeUnit __DoAddition(VolumeUnit right)
 {
     return new Meter3(ConvertToBase().Value + right.ConvertToBase().Value);
 }