Click here to Skip to main content
15,891,033 members
Articles / DevOps / Unit Testing

Units of Measure Library for .NET

Rate me:
Please Sign up or sign in to vote.
4.93/5 (7 votes)
20 Jun 2012CPOL8 min read 60.4K   2K   35  
This article introduces a library for handling units of measure.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Globalization;

namespace HDLibrary.UnitsOfMeasure
{
    /// <summary>
    /// Parses the following formats: 60 s; 60 min;
    /// </summary>
    public class ScaledShiftedUnitParser : IUnitParser
    {
        IUnitParser abbreviatedUnitParser;

        /// <summary>
        /// Creates a new ScaledShiftedUnitParser.
        /// </summary>
        /// <param name="abbreviatedUnitParser">The parser used for resolving the underlaying units.</param>
        public ScaledShiftedUnitParser(IUnitParser abbreviatedUnitParser)
        {
            if (abbreviatedUnitParser == null)
                throw new ArgumentNullException("abbreviatedUnitParser");
            this.abbreviatedUnitParser = abbreviatedUnitParser;
        }

        public Unit ParseUnit(string unitStr, string resultUnitAbbreviation, string resultUnitName, bool throwException)
        {
            string[] items = unitStr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (items.Length != 2)
                return UnitParserExtension.ReturnNullOrThrowFormatException(null, throwException);

            Unit unit = abbreviatedUnitParser.ParseUnit(items[1], null, null, throwException);
            if (unit == null)
                return null;
            try
            {
                double factor = double.Parse(items[0], NumberStyles.Float, CultureInfo.InvariantCulture); //double azAZ
                return new ScaledShiftedUnit(resultUnitAbbreviation, resultUnitName, unit, factor);
            }
            catch (FormatException ex)
            {
                return UnitParserExtension.ReturnNullOrThrowFormatException(null, ex, throwException);
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
Germany Germany
Presently I am a student of computer science at the Karlsruhe Institute of Technology in Germany.

Comments and Discussions