예제 #1
0
    /// <summary>
    /// Converts from this unit of measure to a different unit of measure.
    /// </summary>
    public static double ConvertTo(this UnitOfMeasure sourceUnitOfMeasure, double amount, int precision, UnitOfMeasure finalUnitOfMeasure)
    {
        // If we happen to be the Unit of Measure being requested, return that.
        if (finalUnitOfMeasure == sourceUnitOfMeasure)
            return amount;

        // If the Type of the Unit of Measure differs between the Source and the Destination, we need to throw an error.
        if (sourceUnitOfMeasure.GetUnitOfMeasureType() != finalUnitOfMeasure.GetUnitOfMeasureType())
        {
            throw new InvalidCastException(String.Format("Unit of measures are not of same measurement type: {0} and {1}",
                sourceUnitOfMeasure.GetUnitOfMeasureType(), finalUnitOfMeasure.GetUnitOfMeasureType()));
        }

        // Calculate Source to Primary Unit of Measure
        //      seconds = (60 * (x minutes))
        //      ºK =  (0.5555555556 * (ºF - 32)) + 273.15
        double primaryUnitOfMeasureValue =
            (sourceUnitOfMeasure.GetMultiplier() * (amount + sourceUnitOfMeasure.GetPreCalcAddition())) +
            sourceUnitOfMeasure.GetPostCalcAddition();

        // Here is where we do the conversion from the Primary Unit of Measure to the Requested Destination Measure.  Some examples include.
        //      minutes = ((x seconds - 0) / 60) - 0
        //      ºF = ((ºK - 273.15) / 0.5555555556) + 32.00
        double calculation =
            ((primaryUnitOfMeasureValue - finalUnitOfMeasure.GetPostCalcAddition()) / finalUnitOfMeasure.GetMultiplier()) -
            finalUnitOfMeasure.GetPreCalcAddition();

        // Return the calculation rounded to the precision requested.
        return Math.Round(calculation, precision);
    }