C# PowerShell Other
Latest commit 14920c8 Apr 17, 2017 @anjdreas tools/NuGet.exe: Upgrade to 3.5.0
From 2.4.4-final
Permalink
Failed to load latest commit information.
.teamcity/UnitsNet TeamCity change in 'Units.NET' project: Feb 28, 2017
.vs/config Add more units to FlowRate Jan 21, 2016
Build build.bat: Add colored text sections for each step Apr 17, 2017
Docs/Images Add new logo bitmaps Sep 22, 2014
Samples samples: Add solution with .NET Core console app Oct 22, 2016
Tools Delete Tools/UnitsNet.3.2.0.nupkg Apr 9, 2016
UnitsNet.Serialization.JsonNet.Tests removed element added in error. Dec 12, 2016
UnitsNet.Serialization.JsonNet Modified serilization to support units saved as IComparable (#200) Nov 2, 2016
UnitsNet.TestApps.Uwp.Csharp testapps: Renew test certificates Apr 17, 2017
UnitsNet.TestApps.Uwp.JavaScript testapps: Renew test certificates Apr 17, 2017
UnitsNet.TestApps.Uwp.WinJS testapps: Renew test certificates Apr 17, 2017
UnitsNet.Tests Add ThermalResistance units Apr 14, 2017
UnitsNet GenerateUnits.ps1: Draw summary text with yellow color Apr 17, 2017
tools tools/NuGet.exe: Upgrade to 3.5.0 Apr 17, 2017
.gitattributes .gitattributes: Add back EOL normalization Feb 28, 2017
.gitignore Ignore /secure-file folder Feb 5, 2017
LICENSE Initial commit Jul 19, 2013
README.md README: Add flattr button Mar 24, 2017
UnitsNet.WindowsRuntimeComponent.sln winrt: Use x64 for uwp test apps in Any CPU profile Aug 2, 2016
UnitsNet.WindowsRuntimeComponent.sln.DotSettings Add solution file for Unitsnet.WindowsRuntimeComponent Apr 20, 2016
UnitsNet.sln Add UnitsNet.NetStandard10 project Oct 21, 2016
UnitsNet.sln.DotSettings R#: Use 'Full' cleanup profile for silent cleanup Jan 24, 2017
appveyor.yml appveyor: Fail build on non-zero exit codes Apr 14, 2017
delete-output.bat delete-output.bat: Delete project.lock.json files Apr 17, 2017
fix-eol.bat Add fix-eol.bat Jan 31, 2016
generate-code.bat Rename to generate-code.bat Jan 22, 2017
nuget.config fixup! nuget: Specify nuget.org as default source Oct 21, 2016
opensln.sh Add opensln.sh Jan 22, 2017

README.md

Build status Join the chat at https://gitter.im/UnitsNet/Lobby Flattr this git repo

Units.NET

Everyone have written their share of trivial conversions - or less obvious ones where you need to Google that magic constant.

Stop littering your code with unnecessary calculations. Units.NET gives you all the common units of measurement and the conversions between them. It is light-weight, well-tested and portable.

Installing

Run the following command in the Package Manager Console or go to the NuGet site for the complete relase history.

Install-Package UnitsNet

Build Targets:

  • .NET Standard 1.0
  • Portable 4.0 Profile328 (.NET 4, Silverlight 5, Win8, WinPhone8.1 + WP Silverlight 8)
  • .NET 3.5 Client

Overview

Static Typing

// Convert to the unit of choice - when you need it
Mass weight = GetPersonWeight();
Console.WriteLine("You weigh {0:0.#} kg.", weight.Kilograms);

// Avoid confusing conversions, such as between weight (force) and mass
double weightNewtons = weight.Newtons; // No such thing

// Some popular conversions
Length meter = Length.FromMeters(1);
double cm = meter.Centimeters; // 100
double yards = meter.Yards; // 1.09361
double feet = meter.Feet; // 3.28084
double inches = meter.Inches; // 39.3701

Operator Overloads

// Arithmetic
Length l1 = 2 * Length.FromMeters(1);
Length l2 = Length.FromMeters(1) / 2;
Length l3 = l1 + l2;

// Construct between units
Length distance = Speed.FromKilometersPerHour(80) * TimeSpan.FromMinutes(30);
Acceleration a1 = Speed.FromKilometersPerHour(80) / TimeSpan.FromSeconds(2);
Acceleration a2 = Force.FromNewtons(100) / Mass.FromKilograms(20);
RotationalSpeed r = Angle.FromDegrees(90) / TimeSpan.FromSeconds(2);

Extension Methods

All units have associated extension methods for a really compact, expressive way to construct values or do arithmetic.

using UnitsNet.Extensions.NumberToDuration;
using UnitsNet.Extensions.NumberToLength;
using UnitsNet.Extensions.NumberToTimeSpan;

Speed speed = 30.Kilometers() / 1.Hours(); // 30 km/h (using Duration type)
Length distance = speed * 2.h(); // 60 km (using TimeSpan type)

Acceleration stdGravity = 9.80665.MeterPerSecondSquared();
Force weight = 80.Kilograms() * stdGravity; // 80 kilograms-force or 784.532 newtons

Culture and Localization

The culture for abbreviations defaults to Thread.CurrentUICulture and falls back to US English if not defined. Thread.CurrentCulture affects number formatting unless a custom culture is specified. The relevant methods are:

  • ToString()
  • GetAbbreviation()
  • Parse/TryParse()
  • ParseUnit/TryParseUnit()
var usEnglish = new CultureInfo("en-US");
var russian = new CultureInfo("ru-RU");
var oneKg = Mass.FromKilograms(1);

// ToString() with Thread.CurrentUICulture as US English and Russian respectively
"1 kg" == oneKg.ToString();
"1 кг" == oneKg.ToString();

// ToString() with specific culture and string format pattern
"mg 1.00" == oneKg.ToString(MassUnit.Milligram, usEnglish, "{1} {0:0.00}");
"мг 1,00" == oneKg.ToString(MassUnit.Milligram, russian, "{1} {0:0.00}");

// Parse measurement from string
Mass kg = Mass.Parse(usEnglish, "1.0 kg");
Mass kg = Mass.Parse(russian, "1,0 кг");

// Parse unit from string, a unit can have multiple abbreviations
RotationalSpeedUnit.RevolutionPerMinute == RotationalSpeed.ParseUnit("rpm");
RotationalSpeedUnit.RevolutionPerMinute == RotationalSpeed.ParseUnit("r/min");

// Get default abbreviation for a unit
"kg" == Mass.GetAbbreviation(MassUnit.Kilogram);

Enumerate Units

All units have a unit enum value. Let the user decide what unit of measurement to present the numbers in.

/// <summary>Convert the previous height to the new unit.</summary>
void OnUserChangedHeightUnit(LengthUnit prevUnit, double prevValue, LengthUnit newUnit)
{
    // Construct from dynamic unit and value
    var prevHeight = Length.From(prevValue, prevUnit);

    // Convert to the new unit
    double newHeightValue = prevHeight.As(newUnit);

    // Update UI with the converted value and the newly selected unit
    UpdateHeightUI(newHeightValue, newUnit);
}

Precision and Accuracy

A base unit is chosen for each unit class, represented by a double value (64-bit), and all conversions go via this unit. This means there will always be a small error in both representing other units than the base unit as well as converting between units.

Units.NET was intended for convenience and ease of use, not highly accurate conversions, but I am open to suggestions for improvements.

The tests accept an error up to 1E-5 for most units added so far. Exceptions include units like Teaspoon, where the base unit cubic meter is a lot bigger. In many usecases this is sufficient, but for others this may be a showstopper and something you need to be aware of.

For more details, see Precision.

Serialization

  • UnitsNet.Serialization.JsonNet (nuget, src, tests) for JSON.NET

Important! We cannot guarantee backwards compatibility, although we will strive to do that on a "best effort" basis and bumping the major nuget version when a change is necessary.

The base unit of any unit should be be treated as volatile as we have changed this several times in the history of this library already. Either to reduce precision errors of common units or to simplify code generation. An example is Mass, where the base unit was first Kilogram as this is the SI unit of mass, but in order to use powershell scripts to generate milligrams, nanograms etc. it was easier to choose Gram as the base unit of Mass.

Want To Contribute?

This project is still early and many units and conversions are not yet covered. If you are missing something, please help by contributing or ask for it by creating an issue.

Please read the wiki on Adding a New Unit.

Generally adding a unit involves adding or modifying UnitsNet\UnitDefinitions\*.json files and running generate-code.bat to regenerate the source code and test code stubs, then manually implementing the new unit conversion constants in the test code.

Continuous Integration

AppVeyor performs the following:

  • Build and test all branches
  • Build and test pull requests, notifies on success or error
  • Deploy nugets on master branch, if nuspec versions changed

Who are Using This?

It would be awesome to know who are using this library. If you would like your project listed here, create an issue or edit the README.md and send a pull request. Max logo size is 300x35 pixels and should be in .png, .gif or .jpg formats.

Motion Catalyst logo

Swing Catalyst and Motion Catalyst, Norway

Sports performance applications for Windows and iOS, that combine high-speed video with sensor data to bring facts into your training and visualize the invisible forces at work

Units.NET started here in 2007 when reading strain gauge measurements from force plates and has been very useful in integrating a number of different sensor types into our software and presenting the data in the user's preferred culture and units.

https://www.swingcatalyst.com (for golf)
https://www.motioncatalyst.com (everything else)

- Andreas Gullberg Larsen, CTO (andreas@motioncatalyst.com)

PK Sound logo

PK Sound, Canada

Award-winning performers and composers put everything they’ve got into their music. PK Sound makes sure their fans will hear it all – brilliantly, precisely, consistently.

PK Sound uses UnitsNet in Kontrol - the remote control counterpart to Trinity, the world's only robotic line array solution.

http://www.pksound.ca/pk-sound/announcing-the-official-release-of-kontrol/ (for an idea of what the Kontrol project is)
http://www.pksound.ca/trinity/ (the speakers that Kontrol currently controls)
http://www.pksound.ca/ (everything else)

- Jules LaPrairie, Kontrol software team member

Microsoft.IoT.Devices

Microsoft.IoT.Devices extends Windows IoT Core and makes it easier to support devices like sensors and displays. It provides event-driven access for many digital and analog devices and even provides specialized wrappers for devices like joystick, rotary encoder and graphics display.

http://aka.ms/iotdevices (home page including docs)
http://www.nuget.org/packages/Microsoft.IoT.Devices (NuGet package)