Skip to content

UnitConverter - for dynamic unit conversion #272

@angularsen

Description

@angularsen

I just added some new stuff to make it easier to dynamically convert between units, such as by user choice in a GUI. I was motivated by a stackexchange post, but this scenario has been on my mind for some time.

image

  • New class UnitConverter
  • New property Units on quantities, ex: LengthUnit[] Units { get; } on Length
  • Renamed (obsoleted) UnitClass enum to QuantityType for new naming convention

This allows the following scenario:

// Get quantities for populating quantity UI selector
QuantityType[] quantityTypes = Enum.GetValues(typeof(QuantityType)).Cast<QuantityType>().ToArray();

// If Length is selected, get length units for populating from/to UI selectors
LengthUnit[] lengthUnits = Length.Units;

// Perform conversion by using .ToString() on selected units
double centimeters = UnitConverter.ConvertByName(5, "Length", "Meter", "Centimeter");
double centimeters2 = UnitConverter.ConvertByAbbreviation(5, "Length", "m", "cm");

I did eagerly merge this to master and release a nuget (3.70.0), although I probably should have done a PR first. I still would like to hear your thoughts on the design and any improvements/flaws you can think of.

Test cases:
https://github.com/anjdreas/UnitsNet/blob/master/UnitsNet.Tests/UnitConverterTest.cs

cc @eriove @JKSnd

Ref:
#220 @JenTechSystems
#27 @BrannonKing

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions